From 3f9148da727c56751ac153d95df8ef8117979c09 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:25:21 -0500 Subject: [PATCH 1/2] feat: a thread moves with the threads it started Step 4b, second part (docs/design/fleet.md, Part 3f). A parent moves with its family: ids derived on the receiving side from a family key and each member's source thread, checkouts first then threads parent-first, children waiting off the import slots, shared folders kept shared with guest markers derived on arrival, children left behind becoming their own threads, and children on another computer staying where they are. Rebuilt on main after #981; migration renumbered to 119. --- apps/server/src/guide/topics.ts | 2 +- apps/server/src/links/LinkMoveRepository.ts | 42 +- apps/server/src/links/LinkMoves.test.ts | 341 ++++++++++- apps/server/src/links/LinkMoves.ts | 520 ++++++++++++++++- .../src/links/RemoteChildReactor.test.ts | 60 +- apps/server/src/links/RemoteChildReactor.ts | 32 +- apps/server/src/links/peerRoute.ts | 1 + apps/server/src/moves/MoveQueue.test.ts | 156 ++++- apps/server/src/moves/MoveQueue.ts | 221 +++++++- apps/server/src/moves/ThreadMoves.test.ts | 3 + apps/server/src/moves/ThreadMoves.ts | 163 +++++- apps/server/src/moves/familyMove.ts | 104 ++++ apps/server/src/moves/moveExport.ts | 136 ++++- apps/server/src/moves/threadMoveView.ts | 8 +- .../Layers/ChildThreadReactor.ts | 18 +- .../Layers/ProviderCommandReactor.ts | 23 +- .../src/orchestration/childThreadDecisions.ts | 50 ++ .../orchestration/decider.threadMoves.test.ts | 533 ++++++++++++++++++ apps/server/src/orchestration/decider.ts | 75 ++- .../src/orchestration/threadMoveCarry.ts | 84 ++- .../src/orchestration/threadMoveDecisions.ts | 323 +++++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/119_LinkMoveFamilies.ts | 29 + .../ChatView.move-thread.browser.tsx | 199 ++++++- .../components/MoveThreadsDialogContent.tsx | 75 ++- .../components/ThreadMoveDialogContent.tsx | 123 ++++ .../src/components/chat/threadMoveNotice.tsx | 18 +- .../QuitConfirmationDialog.browser.tsx | 2 + .../desktop/QuitConfirmationDialog.tsx | 11 +- apps/web/src/threadMove.test.ts | 68 +++ apps/web/src/threadMove.ts | 157 +++++- packages/contracts/src/baseSchemas.ts | 7 + packages/contracts/src/moves.ts | 47 +- packages/contracts/src/orchestration.test.ts | 115 +++- packages/contracts/src/orchestration.ts | 85 +++ packages/contracts/src/peerRpc.ts | 45 ++ packages/shared/src/threadMoveProjection.ts | 1 + 37 files changed, 3702 insertions(+), 177 deletions(-) create mode 100644 apps/server/src/moves/familyMove.ts create mode 100644 apps/server/src/persistence/Migrations/119_LinkMoveFamilies.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index c953a409b..d1725b2c8 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -156,7 +156,7 @@ Linking is two-way, with a permission for each direction: "'s agents can star With a link allowed, an agent can start a thread on the other computer in that computer's copy of the project, read it and message it, and its reply comes back. A computer you only open from this app (Settings › Connections › Computers you use from here) is not a link: you see its threads here, but agents can't work across. This app's sign-in to it renews whenever they connect and ends after 90 days without one, or when that computer removes it. Fleet's All computers page and its own page then say the sign-in ended and offer to connect again with a new code; its threads stay on it. -To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, its pull requests come along with auto-fix and auto-merge off (a notice there says what was on, with Turn on), and its plans come along, the waiting one with Implement. Until you send the moved thread a message there, its agent can't use other threads, rooms or schedules. A General Chats thread moves with every file in its folder, up to 100 MB. The dialog says what comes along and what won't work there; the "Moved here" line on the other computer says what arrived and what didn't. If a move doesn't happen, the thread gets back here what the move stopped: its goal and its check-backs, and its queued messages go. A room moves with its agents: the dialog has a row per agent with the matching agent on the other computer picked (same kind and model, else that kind's default), or Leave out. An agent with no match, or left out, arrives as having left, and both ends say which; each agent that comes keeps its own memory or gets the whole conversation once. Move when it's done waits for the agents' hand-offs and replies to finish, and Stop and move now ends them as Stop does. A thread that started other threads, or with a message queued by a scheduled task, another thread or an assistant can't move yet; the dialog says what to finish first.`, +To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, its pull requests come along with auto-fix and auto-merge off (a notice there says what was on, with Turn on), and its plans come along, the waiting one with Implement. Until you send the moved thread a message there, its agent can't use other threads, rooms or schedules. A General Chats thread moves with every file in its folder, up to 100 MB. The dialog says what comes along and what won't work there; the "Moved here" line on the other computer says what arrived and what didn't. If a move doesn't happen, the thread gets back here what the move stopped: its goal and its check-backs, and its queued messages go. A room moves with its agents: the dialog has a row per agent with the matching agent on the other computer picked (same kind and model, else that kind's default), or Leave out. An agent with no match, or left out, arrives as having left, and both ends say which; each agent that comes keeps its own memory or gets the whole conversation once. Move when it's done waits for the agents' hand-offs and replies to finish, and Stop and move now ends them as Stop does. A thread that started other threads moves with them: the dialog lists its threads here, ticked, and one you untick stays here as its own thread, as does one that can't move (the dialog says why). On the other computer the threads that came are still its threads, and its "Moved here" line names the ones that stayed. Threads its agent started on another computer stay there, and the moved thread can't reach them. Move when it's done waits for the threads it started to report back, and Stop and move now ends that wait as Stop does. A thread another thread started moves only with that thread for now. A thread with a message queued by a scheduled task, an assistant or a thread outside its family can't move yet; the dialog says what to finish first.`, }, { id: "devices", diff --git a/apps/server/src/links/LinkMoveRepository.ts b/apps/server/src/links/LinkMoveRepository.ts index 9420233f5..eb5db1155 100644 --- a/apps/server/src/links/LinkMoveRepository.ts +++ b/apps/server/src/links/LinkMoveRepository.ts @@ -28,11 +28,16 @@ import * as SqlSchema from "effect/sql/SqlSchema"; * Where a move stands here, as recorded. `awaiting_approval` with * `stagedApproval` takes its bytes while it waits; the asking computer reads * it as `receiving`, then `staged_awaiting_approval` once every byte is here. + * `waiting_for_family`: a family member's import waits, every byte staged, + * for another member (its parent to commit, or the folder it shares to be + * made; docs/design/fleet.md, Part 3f, review change 2); it holds no slot in + * flight, and the asking computer reads it as `importing`. */ export const LinkMoveStatus = Schema.Literals([ "awaiting_approval", "receiving", "importing", + "waiting_for_family", "committed", "aborted", ]); @@ -78,6 +83,13 @@ export const LinkMoveRow = Schema.Struct({ abortCode: Schema.NullOr(PeerMoveAbortCode), /** An aborted move's clean-up is done. Null on an aborted row: still owed. */ cleanedAt: Schema.NullOr(IsoDateTime), + /** + * A family member's (docs/design/fleet.md, Part 3f, (g)): the family's key + * here, from the link and the family's id. Null: it moves on its own. + */ + familyKey: Schema.NullOr(Schema.String), + /** The thread's id on the computer it left, so another member's import can find this one. */ + sourceThreadId: Schema.NullOr(Schema.String), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -105,9 +117,15 @@ export interface LinkMoveRepositoryShape { readonly stagedApproval: boolean; readonly manifest: PeerMoveManifest; readonly threadId: ThreadId; + readonly familyKey?: string | undefined; readonly reason?: string; readonly now: string; }) => Effect.Effect; + /** A family's member, by its thread's id there: the newest such move. */ + readonly findFamilyMember: ( + familyKey: string, + sourceThreadId: string, + ) => Effect.Effect, LinkMoveRepositoryError>; readonly get: ( linkDeviceId: string, transferId: string, @@ -186,6 +204,8 @@ const make = Effect.gen(function* () { reason AS "reason", abort_code AS "abortCode", cleaned_at AS "cleanedAt", + family_id AS "familyKey", + source_thread_id AS "sourceThreadId", created_at AS "createdAt", updated_at AS "updatedAt" FROM link_moves @@ -211,17 +231,33 @@ const make = Effect.gen(function* () { const get: LinkMoveRepositoryShape["get"] = (linkDeviceId, transferId) => findOne({ linkDeviceId, transferId }).pipe(wrap("get")); + const findMember = SqlSchema.findOneOption({ + Request: Schema.Struct({ familyKey: Schema.String, sourceThreadId: Schema.String }), + Result: LinkMoveDbRow, + execute: ({ familyKey, sourceThreadId }) => + sql.unsafe( + `${select} WHERE family_id = ? AND source_thread_id = ? ORDER BY created_at DESC, transfer_id DESC LIMIT 1`, + [familyKey, sourceThreadId], + ), + }); + + const findFamilyMember: LinkMoveRepositoryShape["findFamilyMember"] = ( + familyKey, + sourceThreadId, + ) => findMember({ familyKey, sourceThreadId }).pipe(wrap("findFamilyMember")); + const insert: LinkMoveRepositoryShape["insert"] = (input) => Effect.gen(function* () { const manifest = yield* encodeManifest(input.manifest); yield* sql` INSERT INTO link_moves ( link_device_id, transfer_id, transfer_key, status, staged_approval, manifest_json, - bytes_received, thread_id, reason, created_at, updated_at + bytes_received, thread_id, reason, family_id, source_thread_id, created_at, updated_at ) VALUES ( ${input.linkDeviceId}, ${input.transferId}, ${input.transferKey}, ${input.status}, ${input.stagedApproval ? 1 : 0}, ${manifest}, 0, ${input.threadId}, - ${input.reason ?? null}, ${input.now}, ${input.now} + ${input.reason ?? null}, ${input.familyKey ?? null}, ${input.manifest.source.threadId}, + ${input.now}, ${input.now} ) ON CONFLICT(link_device_id, transfer_id) DO NOTHING `; @@ -307,7 +343,7 @@ const make = Effect.gen(function* () { markArrived, listUnarrived, insert, - + findFamilyMember, get, listOpen, listCleanupOwed, diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index 81d87f526..bc2371732 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -12,6 +12,7 @@ import { ProviderDriverKind, ProviderInstanceId, ThreadId, + ThreadMoveFamilyId, ThreadMoveId, ThreadParticipantId, TurnId, @@ -58,9 +59,11 @@ import { import { RelayDeviceRepository } from "../relay/RelayDeviceRepository.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; -import { LinkMoveRepositoryLive } from "./LinkMoveRepository.ts"; +import { LinkMoveRepository, LinkMoveRepositoryLive } from "./LinkMoveRepository.ts"; import { binaryPatchBytes, + linkFamilyKey, + linkFamilyThreadId, linkMoveKey, linkMoveThreadId, LinkMoves, @@ -254,7 +257,25 @@ function testLayer( } as never), getThreadShellById: () => Effect.succeed(Option.fromUndefinedOr(carry.shell?.())), }), - Layer.mock(ProjectionThreadRepository)({ getById: () => Effect.succeed(Option.none()) }), + // A thread here once its import was dispatched (a family's child reads its parent). + Layer.mock(ProjectionThreadRepository)({ + getById: ({ threadId }) => + Effect.succeed( + Option.fromUndefinedOr( + dispatched + .filter((command) => command.type === "thread.import") + .find((command) => command.threadId === threadId) === undefined + ? undefined + : ({ + threadId, + projectId: ProjectId.make("project-b"), + deletedAt: null, + move: null, + pendingMove: null, + } as never), + ), + ), + }), Layer.mock(RelayDeviceRepository)({ getDevice: () => Effect.succeed(Option.none()) }), // Every agent here is a Claude whose home is `carry.home`. Layer.mock(ProviderService)({ @@ -311,19 +332,24 @@ const pack = ( repos: ReturnType, nativeSession?: NativeSessionExport | null, state?: PeerMoveThreadState, - room?: Pick & { + room?: Pick & { readonly thread?: OrchestrationThread; + /** Another thread of the same checkout (a family member), as its own transfer. */ + readonly threadId?: ThreadId; + readonly transferId?: ThreadMoveId; }, ) => Effect.gen(function* () { const git = yield* GitVcsDriver.GitVcsDriver; const checkout = yield* inspectMoveCheckout(git, repos.a, "origin"); - const dir = path.join(repos.root, "export"); + const transferId = room?.transferId ?? TRANSFER; + const dir = path.join(repos.root, "export", transferId); const manifest = yield* writeMoveExport({ git, checkout, - transferId: TRANSFER, + transferId, dir, + family: room?.family, attachmentsDir: path.join(repos.root, "attachments"), thread: room?.thread ?? movingThread(), room: room?.room, @@ -334,7 +360,7 @@ const pack = ( source: { environmentId: EnvironmentId.make("environment-windows"), environmentLabel: "Windows PC", - threadId: ThreadId.make("thread-a"), + threadId: room?.threadId ?? ThreadId.make("thread-a"), }, agent, nativeSession, @@ -343,22 +369,31 @@ const pack = ( return { manifest, payload: fs.readFileSync(movePayloadPath(dir)), checkout }; }); -/** Offers, sends and finishes a packed move, then waits for its import to settle. */ -const deliver = (manifest: PeerMoveManifest, payload: Buffer) => +/** + * Offers, sends and finishes a packed move, then waits for its import to + * settle (with `settle: false`, only until it is handed to the import). + */ +const deliver = ( + manifest: PeerMoveManifest, + payload: Buffer, + transferId: ThreadMoveId = TRANSFER, + options: { readonly settle?: boolean } = {}, +) => Effect.gen(function* () { const moves = yield* LinkMoves; - yield* moves.prepare(link("allowed"), { transferId: TRANSFER, manifest }); + yield* moves.prepare(link("allowed"), { transferId, manifest }); for (let offset = 0; offset < payload.length; offset += 64 * 1024) { yield* moves.chunk(link("allowed"), { - transferId: TRANSFER, + transferId, offset, data: payload.subarray(offset, offset + 64 * 1024).toString("base64"), }); } - let state = yield* moves.finish(link("allowed"), { transferId: TRANSFER }); + let state = yield* moves.finish(link("allowed"), { transferId }); + if (options.settle === false) return state; for (let tries = 0; tries < 200 && state.status === "importing"; tries += 1) { yield* Effect.sleep("50 millis"); - state = yield* moves.status(link("allowed"), { transferId: TRANSFER }); + state = yield* moves.status(link("allowed"), { transferId }); } return state; }); @@ -1599,3 +1634,285 @@ describe("what a move may write here", () => { ); }); }); + +describe("a family moving here (Part 3f, (g))", () => { + const FAMILY = ThreadMoveFamilyId.make("family-1"); + const PARENT = ThreadId.make("thread-a"); + const CHILD = ThreadId.make("thread-c1"); + const OTHER_CHILD = ThreadId.make("thread-c2"); + const familyKey = linkFamilyKey("device-windows", FAMILY); + const parentHere = linkFamilyThreadId(familyKey, PARENT); + const childHere = linkFamilyThreadId(familyKey, CHILD); + const transfer = (name: string) => ThreadMoveId.make(`transfer-${name}`); + const imports = (dispatched: ReadonlyArray) => + dispatched.flatMap((command) => (command.type === "thread.import" ? [command] : [])); + /** Waits until the move's row reads `status` here. */ + const untilStatus = (transferId: ThreadMoveId, status: string) => + Effect.gen(function* () { + const rows = yield* LinkMoveRepository; + for (let tries = 0; tries < 200; tries += 1) { + const row = yield* rows.get("device-windows", transferId); + if (Option.isSome(row) && row.value.status === status) return row.value; + yield* Effect.sleep("50 millis"); + } + return assert.fail(`${transferId} never reached ${status}`); + }); + + it.live( + "children that arrive first wait for their parent holding no slot, then land under it", + () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const child = (threadId: ThreadId, name: string) => + pack(repos, null, undefined, { + threadId, + transferId: transfer(name), + family: { id: FAMILY, parentThreadId: PARENT, parentTurnId: TurnId.make("turn-1") }, + }); + const first = yield* child(CHILD, "c1"); + const second = yield* child(OTHER_CHILD, "c2"); + // Two children, as many as one link moves here at once: both wait. + for (const [packed, name] of [ + [first, "c1"], + [second, "c2"], + ] as const) { + const state = yield* deliver(packed.manifest, packed.payload, transfer(name), { + settle: false, + }); + assert.equal(state.status, "importing"); + yield* untilStatus(transfer(name), "waiting_for_family"); + } + assert.deepEqual(imports(dispatched), []); + // Their waits hold no slot: the parent is taken, and lands first. + const parent = yield* pack(repos, null, undefined, { + transferId: transfer("p"), + family: { id: FAMILY, stayed: [{ title: "Review notes" }] }, + }); + const landed = yield* deliver(parent.manifest, parent.payload, transfer("p")); + assert.equal(landed.status, "committed"); + yield* untilStatus(transfer("c1"), "committed"); + yield* untilStatus(transfer("c2"), "committed"); + const [parentImport, ...childImports] = imports(dispatched); + assert.equal(parentImport?.threadId, parentHere); + assert.equal(parentImport?.movedFrom.familyKey, familyKey); + assert.include( + parentImport?.arrival?.left ?? [], + "1 thread it started stayed on Windows PC: Review notes.", + ); + assert.deepEqual( + childImports.map((command) => command.lineage?.parentThreadId).toSorted(), + [parentHere, parentHere], + ); + // Its turn there is named as the parent's history names it here. + assert.equal( + childImports[0]?.lineage?.parentTurnId, + parentImport?.messages.find((message) => message.turnId !== null)?.turnId, + ); + // The three manifests carry the same message ids there; here no two + // members share one (one would move another's message). + const ids = [parentImport, ...childImports].flatMap((command) => + (command?.messages ?? []).map((message) => message.messageId), + ); + assert.equal(ids.length, 6); + assert.equal(new Set(ids).size, ids.length); + }).pipe(Effect.provide(testLayer(repos, dispatched))); + }, + ); + + it.live("a child whose parent is dropped is dropped too", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const child = yield* pack(repos, null, undefined, { + threadId: CHILD, + transferId: transfer("c1"), + family: { id: FAMILY, parentThreadId: PARENT }, + }); + yield* deliver(child.manifest, child.payload, transfer("c1"), { settle: false }); + yield* untilStatus(transfer("c1"), "waiting_for_family"); + const parent = yield* pack(repos, null, undefined, { + transferId: transfer("p"), + family: { id: FAMILY }, + }); + const moves = yield* LinkMoves; + yield* moves.prepare(link("allowed"), { + transferId: transfer("p"), + manifest: parent.manifest, + }); + yield* moves.abort(link("allowed"), { transferId: transfer("p") }); + const dropped = yield* untilStatus(transfer("c1"), "aborted"); + assert.equal(dropped.reason, "Its parent thread didn't move."); + assert.deepEqual(imports(dispatched), []); + }).pipe(Effect.provide(testLayer(repos, dispatched))); + }); + + it.live( + "a member in a folder whose owner was dropped ends, and two members never hold each other's locks", + () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const moves = yield* LinkMoves; + // One child makes its folder and waits for the parent; its sibling + // works in that folder and waits too. + const owner = yield* pack(repos, null, undefined, { + threadId: CHILD, + transferId: transfer("c1"), + family: { id: FAMILY, parentThreadId: PARENT }, + }); + yield* deliver(owner.manifest, owner.payload, transfer("c1"), { settle: false }); + yield* untilStatus(transfer("c1"), "waiting_for_family"); + const sibling = yield* pack(repos, null, undefined, { + threadId: OTHER_CHILD, + transferId: transfer("c2"), + family: { id: FAMILY, parentThreadId: PARENT, sharesCheckoutOf: CHILD }, + }); + yield* deliver(sibling.manifest, sibling.payload, transfer("c2"), { settle: false }); + const waiting = yield* untilStatus(transfer("c2"), "waiting_for_family"); + assert.equal(waiting.stage, "applied"); + // The folder's owner is dropped: its sharer can't stay pointing at it. + yield* moves.abort(link("allowed"), { transferId: transfer("c1") }); + const ended = yield* untilStatus(transfer("c2"), "aborted"); + assert.equal(ended.reason, "The thread whose folder it works in didn't move."); + // The owner offered again, now in its sibling's folder: a sharer is + // nobody's folder, so it ends rather than waiting on it. + const again = yield* pack(repos, null, undefined, { + threadId: CHILD, + transferId: transfer("c1-again"), + family: { id: FAMILY, parentThreadId: PARENT, sharesCheckoutOf: OTHER_CHILD }, + }); + yield* deliver(again.manifest, again.payload, transfer("c1-again"), { settle: false }); + yield* untilStatus(transfer("c1-again"), "aborted"); + // The parent lands on its own; nothing waits on a lock. + const parent = yield* pack(repos, null, undefined, { + transferId: transfer("p"), + family: { id: FAMILY }, + }); + const landed = yield* deliver(parent.manifest, parent.payload, transfer("p")); + assert.equal(landed.status, "committed"); + assert.deepEqual( + imports(dispatched).map((command) => command.threadId), + [parentHere], + ); + }).pipe(Effect.provide(testLayer(repos, dispatched))); + }, + ); + + it.live( + "a parent working in its child's folder lands with it, neither waiting on the other", + () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + const setupRuns: string[] = []; + return Effect.gen(function* () { + // The parent works in the child's worktree there: the child sends the + // folder, the parent none of it. + const parent = yield* pack(repos, null, undefined, { + transferId: transfer("p"), + family: { id: FAMILY, sharesCheckoutOf: CHILD }, + }); + assert.deepEqual( + parent.manifest.parts.filter((part) => part.kind !== "attachment"), + [], + ); + const child = yield* pack(repos, null, undefined, { + threadId: CHILD, + transferId: transfer("c1"), + family: { id: FAMILY, parentThreadId: PARENT }, + }); + yield* deliver(parent.manifest, parent.payload, transfer("p"), { settle: false }); + yield* untilStatus(transfer("p"), "waiting_for_family"); + yield* deliver(child.manifest, child.payload, transfer("c1"), { settle: false }); + yield* untilStatus(transfer("p"), "committed"); + const childRow = yield* untilStatus(transfer("c1"), "committed"); + const [parentImport, childImport] = imports(dispatched); + assert.equal(parentImport?.threadId, parentHere); + assert.equal(childImport?.threadId, childHere); + assert.equal(parentImport?.worktreePath, childRow.worktreePath); + assert.equal(parentImport?.branch, childRow.branch); + // A guest there, as here: never the folder's owner. + assert.deepEqual(parentImport?.worktreeOrigin, { kind: "thread", threadId: childHere }); + assert.equal(childImport?.lineage?.parentThreadId, parentHere); + // The folder's own move ran its setup, once. + assert.deepEqual(setupRuns, [childRow.worktreePath]); + assert.equal( + fs.readFileSync(path.join(childRow.worktreePath!, "c.txt"), "utf8"), + "c.txt unstaged\n", + ); + }).pipe(Effect.provide(testLayer(repos, dispatched, "allowed", () => false, setupRuns))); + }, + ); + + it.live("a child in its parent's folder takes it, and one dropped takes nothing of it", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const parent = yield* pack(repos, null, undefined, { + transferId: transfer("p"), + family: { id: FAMILY }, + }); + yield* deliver(parent.manifest, parent.payload, transfer("p")); + const parentRow = yield* untilStatus(transfer("p"), "committed"); + const folder = parentRow.worktreePath!; + // A sharer offered and dropped before it lands: nothing of the folder goes. + const dropped = yield* pack(repos, null, undefined, { + threadId: OTHER_CHILD, + transferId: transfer("c2"), + family: { id: FAMILY, parentThreadId: PARENT, sharesCheckoutOf: PARENT }, + }); + const moves = yield* LinkMoves; + yield* moves.prepare(link("allowed"), { + transferId: transfer("c2"), + manifest: dropped.manifest, + }); + yield* moves.abort(link("allowed"), { transferId: transfer("c2") }); + yield* untilStatus(transfer("c2"), "aborted"); + assert.isTrue(fs.existsSync(path.join(folder, "c.txt"))); + // One that lands takes the parent's folder and branch, as a guest. + const child = yield* pack(repos, null, undefined, { + threadId: CHILD, + transferId: transfer("c1"), + family: { id: FAMILY, parentThreadId: PARENT, sharesCheckoutOf: PARENT }, + }); + const landed = yield* deliver(child.manifest, child.payload, transfer("c1")); + assert.equal(landed.status, "committed"); + const childImport = imports(dispatched).find((command) => command.threadId === childHere); + assert.equal(childImport?.worktreePath, folder); + assert.deepEqual(childImport?.worktreeOrigin, { kind: "thread", threadId: parentHere }); + assert.equal(childImport?.lineage?.parentThreadId, parentHere); + assert.isTrue(fs.existsSync(path.join(folder, "c.txt"))); + }).pipe(Effect.provide(testLayer(repos, dispatched))); + }); + + it("refuses a family member that names itself, or carries files into another's folder", () => { + const base = { + totalBytes: 0, + sha256: "x", + parts: [], + source: { environmentId: "e", environmentLabel: "Windows PC", threadId: CHILD }, + git: { headSha: "h", branch: null, baseSha: null }, + thread: { messages: [], activities: [] }, + } as unknown as PeerMoveManifest; + assert.include( + moveManifestRefusal({ ...base, family: { id: FAMILY, parentThreadId: CHILD } }), + "itself as its parent", + ); + assert.include( + moveManifestRefusal({ ...base, family: { id: FAMILY, sharesCheckoutOf: CHILD } }), + "shares its own folder", + ); + assert.include( + moveManifestRefusal({ + ...base, + totalBytes: 4, + parts: [{ kind: "file", offset: 0, length: 4, sha256: "y", path: "a.txt", mode: "file" }], + family: { id: FAMILY, sharesCheckoutOf: PARENT }, + }), + "carries none of its files", + ); + assert.isNull( + moveManifestRefusal({ ...base, family: { id: FAMILY, sharesCheckoutOf: PARENT } }), + ); + }); +}); diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 7ab0cc3ed..15913ec21 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -29,7 +29,7 @@ import * as NodeZlib from "node:zlib"; import { type ChatAttachment, - type ChildRequestId, + ChildRequestId, CommandId, type ComputerLinkPendingRequest, ComputerLinkError, @@ -60,6 +60,7 @@ import { type ThreadMovedFrom, type RuntimeMode, PEER_MOVE_CHUNK_MAX_BYTES, + PEER_MOVE_FAMILY_MAX_STAYED, PEER_MOVE_ROOM_MAX_PARTICIPANTS, PEER_MOVE_STATE_MAX_BYTES, PEER_MOVE_STATE_MAX_CHECK_BACKS, @@ -85,6 +86,7 @@ import * as PubSub from "effect/PubSub"; import * as Schedule from "effect/Schedule"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; import { resolveAttachmentPath, toSafeThreadAttachmentSegment } from "../attachmentStore.ts"; import { ServerConfig } from "../config.ts"; @@ -131,6 +133,12 @@ import { LinkRequests, linkIdentityRefusal, type PeerLink } from "./LinkRequests /** A move nobody allowed, or that stopped arriving, ends after a day. */ export const LINK_MOVE_TTL_MS = 24 * 60 * 60 * 1000; +/** + * A family member that arrived and waits for a relative (its parent can wait + * on its other threads for a long time) waits a week before it ends. The + * computer it left drops it sooner once that relative's move ends there. + */ +export const LINK_MOVE_FAMILY_TTL_MS = 7 * LINK_MOVE_TTL_MS; /** * Moves in flight one link may have here at once, and all links together: * every unfinished move except one held for this computer's user with every @@ -215,6 +223,12 @@ export class LinkMoves extends Context.Service()( /** An import stage that can't go on: the move ends aborted with this reason. */ class ImportStop extends Data.TaggedError("ImportStop")<{ readonly reason: string }> {} +/** How a family's child lands here: under its parent, or as its own thread with why. */ +interface FamilyLanding { + readonly lineage?: { readonly parentThreadId: ThreadId; readonly parentTurnId: TurnId | null }; + readonly left?: string; +} + const nowIso = Effect.map(DateTime.now, DateTime.formatIso); /** hash(link, transfer): every resource a move makes here is named from it. */ @@ -225,6 +239,55 @@ export const linkMoveKey = (linkDeviceId: string, transferId: string) => export const linkMoveThreadId = (transferKey: string) => ThreadId.make(derivedUuid("link-move-thread", transferKey)); +/** + * hash(link, family id): a family's key here (docs/design/fleet.md, Part 3f, + * (g)). Its members' threads, turns and messages are named from it and their + * ids there, so each can name the others before they arrive. From the link + * the move came over, so no other computer can name a family's threads. + */ +export const linkFamilyKey = (linkDeviceId: string, familyId: string) => + createHash("sha256").update(`family\u0000${linkDeviceId}\u0000${familyId}`).digest("hex"); + +/** A family member's thread here, from its family's key and its id there. */ +export const linkFamilyThreadId = (familyKey: string, sourceThreadId: string) => + ThreadId.make(derivedUuid("link-move-family-thread", familyKey, sourceThreadId)); + +/** + * A moved message's id here: from the move's transfer key, or for a family + * member from the family's key and the member's own thread there, so two + * members never name a message alike whatever ids their manifests carry. + */ +export const linkMoveMessageId = ( + row: Pick, + id: string, +) => + MessageId.make( + row.familyKey === null + ? derivedUuid("link-move-message", row.transferKey, id) + : derivedUuid("link-move-message", row.familyKey, row.manifest.source.threadId, id), + ); + +/** + * A moved turn's id here, as linkMoveMessageId names messages. `sourceThreadId` + * is the thread there whose turn it is: a child names its parent's turn as + * the parent's own import names it. + */ +export const linkMoveTurnId = ( + row: Pick, + sourceThreadId: string, + id: string, +) => + TurnId.make( + row.familyKey === null + ? derivedUuid("link-move-turn", row.transferKey, id) + : derivedUuid("link-move-turn", row.familyKey, sourceThreadId, id), + ); + +/** The words a child's move ends with when its parent's didn't land here. */ +const PARENT_DIDNT_MOVE = "Its parent thread didn't move."; +/** The words a member's move ends with when the folder it works in didn't come. */ +const OWNER_DIDNT_MOVE = "The thread whose folder it works in didn't move."; + const isWindows = process.platform === "win32"; const isCaseInsensitive = process.platform === "win32" || process.platform === "darwin"; const foldCase = (path: string) => (isCaseInsensitive ? path.toLowerCase() : path); @@ -282,7 +345,46 @@ export function moveManifestRefusal(manifest: PeerMoveManifest): string | null { if (ownSessionParts > 0 !== (manifest.session !== undefined)) { return "its session doesn't match its files"; } - return moveRoomRefusal(manifest) ?? moveStateRefusal(manifest.thread.state); + return ( + moveRoomRefusal(manifest) ?? + moveFamilyRefusal(manifest) ?? + moveStateRefusal(manifest.thread.state) + ); +} + +/** + * Why a moved family member can't be taken, or null (docs/design/fleet.md, + * Part 3f, (g)): it names neither itself as its parent nor its own folder's + * owner, a parent's turn only with the parent, and lists within bounds. One + * that shares another's folder carries none of the folder's files and no + * commits of its own; a general chat shares no folder. + */ +function moveFamilyRefusal(manifest: PeerMoveManifest): string | null { + const family = manifest.family; + if (family === undefined) return null; + const self = manifest.source.threadId; + if (family.parentThreadId === self) return "it names itself as its parent"; + if (family.parentTurnId !== undefined && family.parentThreadId === undefined) { + return "it names a parent's turn without its parent"; + } + if ( + (family.stayed ?? []).length > PEER_MOVE_FAMILY_MAX_STAYED || + (family.remoteStayed ?? []).length > PEER_MOVE_FAMILY_MAX_STAYED + ) { + return "it names too many threads"; + } + if (family.sharesCheckoutOf === undefined) return null; + if (family.sharesCheckoutOf === self) return "it shares its own folder"; + if (isScratchMoveManifest(manifest)) return "a general chat shares no folder"; + if (manifest.git.baseSha !== null) return "a thread in another's folder carries no commits"; + if ( + manifest.parts.some( + (part) => part.kind === "bundle" || part.kind === "diff" || part.kind === "file", + ) + ) { + return "a thread in another's folder carries none of its files"; + } + return null; } /** @@ -460,6 +562,28 @@ const make = Effect.gen(function* () { const setupScripts = yield* ProjectSetupScriptRunner; const environment = yield* ServerEnvironment; const providers = yield* ProviderService; + const sql = yield* SqlClient.SqlClient; + + /** Whether any of `messages` has an id a thread other than `threadId` already holds here. */ + const messageIdsTaken = ( + threadId: ThreadId, + messages: ReadonlyArray<{ readonly messageId: string }>, + ) => + Effect.gen(function* () { + const ids = messages.map((message) => message.messageId); + for (let start = 0; start < ids.length; start += 500) { + const chunk = ids.slice(start, start + 500); + const rows = yield* sql<{ readonly found: number }>` + SELECT 1 AS "found" FROM projection_thread_messages + WHERE thread_id <> ${threadId} AND message_id IN ${sql.in(chunk)} + LIMIT 1 + `; + if (rows.length > 0) return true; + } + return false; + }).pipe( + Effect.mapError(() => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` })), + ); // GitHub's sign-in, for the pull request switches a move brings; none in a // server built without it (tests), which then can't tell. const gitHubCli = yield* Effect.serviceOption(GitHubCli); @@ -487,6 +611,8 @@ const make = Effect.gen(function* () { const scope = yield* Effect.scope; /** Imports running in this process, so a second `finish` doesn't start another. */ const importing = new Set(); + /** Imports asked to start while they were ending: each runs once more (runImport). */ + const importAgain = new Set(); const peerFailure = (detail: string) => new PeerRpcError({ detail }); const stagingDir = (row: Pick) => @@ -507,7 +633,7 @@ const make = Effect.gen(function* () { ? row.bytesReceived >= row.manifest.totalBytes ? "staged_awaiting_approval" : "receiving" - : waitingToImport(row) + : waitingToImport(row) || row.status === "waiting_for_family" ? "importing" : row.status; const stateOf = (row: LinkMoveRow): PeerMoveState => ({ @@ -537,16 +663,22 @@ const make = Effect.gen(function* () { row.status === "receiving" && row.stagedApproval && row.bytesReceived >= row.manifest.totalBytes; - /** Holds no slot in flight: waiting for Allow, or for a slot, with every byte here. */ - const holdsNoSlot = (row: LinkMoveRow) => staged(row) || waitingToImport(row); + /** + * Holds no slot in flight: waiting for Allow, or for a slot, with every + * byte here; or waiting for another member of its family (Part 3f, review + * change 2), so the member it waits for can always get one. + */ + const holdsNoSlot = (row: LinkMoveRow) => + staged(row) || waitingToImport(row) || row.status === "waiting_for_family"; /** * Counts against the link's staging budget: sent before Allow, and its bytes * still in staging, waiting for Allow (all here or still arriving) or, - * allowed, waiting for an import slot. Its import holds a slot in flight - * instead. + * allowed, waiting for an import slot; or waiting for its family. Its import + * holds a slot in flight instead. */ const holdsStaging = (row: LinkMoveRow) => - row.stagedApproval && (row.status === "awaiting_approval" || waitingToImport(row)); + row.status === "waiting_for_family" || + (row.stagedApproval && (row.status === "awaiting_approval" || waitingToImport(row))); /** A move's row. Fails when it couldn't be read: an outage must never read as "never heard of it". */ const readRow = (linkDeviceId: string, transferId: string) => @@ -674,6 +806,20 @@ const make = Effect.gen(function* () { .pipe(Effect.ignore); return; } + // A family's folder that a member still coming shares (docs/design/ + // fleet.md, Part 3f, (g)) stays until that member lands (then a thread + // uses it) or is dropped: clean-up stays owed, and the sweep tries again. + if (row.familyKey !== null && row.manifest.family?.sharesCheckoutOf === undefined) { + const open = yield* moves.listOpen.pipe(Effect.option); + const sharedStill = + Option.isNone(open) || + open.value.some( + (entry) => + entry.familyKey === row.familyKey && + entry.manifest.family?.sharesCheckoutOf === row.sourceThreadId, + ); + if (sharedStill) return; + } // The repository recorded when the import began (nothing was made in // git before that). One deleted since took its refs and worktree list // with it; one that is there but can't be read, or can't be told @@ -883,6 +1029,9 @@ const make = Effect.gen(function* () { if (settled) { if (row.status === "awaiting_approval") yield* announcePending; yield* cleanUp({ ...row, status: "aborted", reason, abortCode: abortCode ?? null }); + // Its family's members waiting on it (Part 3f, (g)) end too, and a + // slot it held goes to the next one: looked at once this lock is let go. + yield* Effect.suspend(() => startImports).pipe(Effect.forkIn(scope)); } return settled; }); @@ -933,6 +1082,21 @@ const make = Effect.gen(function* () { return gone(`${participant.handle}: ${resolved.refused}`); } } + // A family member (Part 3f, (g)): its thread is named from the + // family's key here, so its relatives can name it before it lands. + // One member moves here once. + const familyKey = + manifest.family !== undefined + ? linkFamilyKey(link.deviceId, manifest.family.id) + : undefined; + if (familyKey !== undefined) { + const earlier = yield* moves + .findFamilyMember(familyKey, manifest.source.threadId) + .pipe(Effect.mapError(() => peerFailure(`${ownLabel()} couldn't read its moves.`))); + if (Option.isSome(earlier) && earlier.value.status !== "aborted") { + return gone("That thread is already moving here with its family."); + } + } // An asking computer that reads the codes is told why a refusal // came; an older one is answered exactly as before. const asksStaged = input.stagedApproval === true; @@ -947,7 +1111,23 @@ const make = Effect.gen(function* () { if (!current.ok) return gone(current.text); const held = current.access === "ask" && asksStaged; const open = yield* moves.listOpen; - if (held) { + // A family member may wait here for its relatives holding no + // slot (Part 3f, review change 2): it counts against the staging + // budget from the start, as a move held for Allow does. One its + // relatives here already wait for (their parent, or the folder + // they share) is never refused for their waits: the member they + // wait for can always come. + const source = manifest.source.threadId; + const awaited = + familyKey !== undefined && + open.some( + (entry) => + entry.familyKey === familyKey && + entry.status === "waiting_for_family" && + (entry.manifest.family?.parentThreadId === source || + entry.manifest.family?.sharesCheckoutOf === source), + ); + if ((held || familyKey !== undefined) && !awaited) { const waiting = open.filter( (entry) => entry.linkDeviceId === link.deviceId && holdsStaging(entry), ); @@ -957,7 +1137,9 @@ const make = Effect.gen(function* () { bytes + manifest.totalBytes > MAX_STAGED_BYTES_PER_LINK ) { return refused( - `${ownLabel()} is holding other moves until its user allows them.`, + held + ? `${ownLabel()} is holding other moves until its user allows them.` + : `${ownLabel()} is holding as many moves as it can while their families arrive.`, "staging_full", ); } @@ -980,7 +1162,11 @@ const make = Effect.gen(function* () { status: current.access === "ask" ? "awaiting_approval" : "receiving", stagedApproval: held, manifest, - threadId: linkMoveThreadId(transferKey), + threadId: + familyKey !== undefined + ? linkFamilyThreadId(familyKey, manifest.source.threadId) + : linkMoveThreadId(transferKey), + familyKey, now: yield* nowIso, }); }), @@ -1142,8 +1328,14 @@ const make = Effect.gen(function* () { */ const settleLanded = (row: LinkMoveRow) => Effect.gen(function* () { - // A general chat's folder gets no setup script: it isn't a project's worktree. - if (row.worktreePath !== null && !isScratchMoveManifest(row.manifest)) { + // A general chat's folder gets no setup script: it isn't a project's + // worktree. Nor does a family member's in another's folder: that + // folder's own move ran it. + if ( + row.worktreePath !== null && + !isScratchMoveManifest(row.manifest) && + row.manifest.family?.sharesCheckoutOf === undefined + ) { const land = yield* landing(row.manifest); if (land !== null) { yield* setupScripts @@ -1246,6 +1438,68 @@ const make = Effect.gen(function* () { const stop = (reason: string) => Effect.fail(new ImportStop({ reason })); + /** Whether a member's folder is made here: its owner's move applied its files, or landed. */ + const folderMade = (owner: LinkMoveRow) => + owner.status === "committed" || owner.stage === "applied" || owner.stage === "arrived"; + + /** + * Where a family member's import stands against its relatives (docs/design/ + * fleet.md, Part 3f, review change 3). First folders: a member in another's + * folder waits only until that folder is made here, in no order among + * folders, so a parent working in its child's folder can't wait on itself. + * Then threads: a child commits only once its parent has. `stop` when the + * one it waits for was dropped; `wait` while it may still come. + */ + const familyGate = (row: LinkMoveRow) => + Effect.gen(function* () { + const family = row.manifest.family; + const key = row.familyKey; + if (family === undefined || key === null) return { kind: "ready" } as const; + const member = (sourceThreadId: string) => + moves + .findFamilyMember(key, sourceThreadId) + .pipe(Effect.mapError(() => peerFailure(`${ownLabel()} couldn't read its moves.`))); + // A member in another's folder, at any stage before it lands: the + // folder's owner must still be coming, and own a folder of its own (a + // sharer can't be one's owner). One dropped meanwhile ends it, never + // leaves it pointing at a folder nobody moved. + if (family.sharesCheckoutOf !== undefined) { + const owner = yield* member(family.sharesCheckoutOf); + if (Option.isNone(owner)) { + if (row.stage === null) return { kind: "wait" } as const; + return { kind: "stop", reason: OWNER_DIDNT_MOVE } as const; + } + if ( + owner.value.status === "aborted" || + owner.value.manifest.family?.sharesCheckoutOf !== undefined + ) { + return { kind: "stop", reason: OWNER_DIDNT_MOVE } as const; + } + if (row.stage === null) { + return folderMade(owner.value) + ? ({ kind: "ready" } as const) + : ({ kind: "wait" } as const); + } + } + if (row.stage === "applied" && family.parentThreadId !== undefined) { + const parent = yield* member(family.parentThreadId); + if (Option.isNone(parent)) return { kind: "wait" } as const; + if (parent.value.status === "aborted") { + return { kind: "stop", reason: PARENT_DIDNT_MOVE } as const; + } + return parent.value.status === "committed" + ? ({ kind: "ready" } as const) + : ({ kind: "wait" } as const); + } + return { kind: "ready" } as const; + }); + + /** + * A member in another's folder skips the git stages: once that folder is + * made here it goes straight to its commit, where it takes the folder. + */ + const sharerStage = (row: LinkMoveRow) => setStage(row, { stage: "applied" }); + const partBytes = (row: LinkMoveRow, part: PeerMovePart) => Effect.tryPromise(async () => { // An empty file: nothing to read (a payload of only those has no file). @@ -1910,8 +2164,134 @@ const make = Effect.gen(function* () { ), ); - /** The thread itself, and with it the commit. Waits for the engine's answer without letting go. */ - const commitStage = (row: LinkMoveRow) => + /** + * A family member as it lands here (docs/design/fleet.md, Part 3f, (g)), + * every id named from the family's key, which this computer derived from + * the link it came over: requests and reports between members, the folder + * it shares (its guest marker, from the family, never a path the other + * computer named), the parent it lands under, and the "Moved here" words + * for what stayed. Null for a thread that moves on its own. + */ + const familyOf = (row: LinkMoveRow) => { + const family = row.manifest.family; + const key = row.familyKey; + if (family === undefined || key === null) return null; + const threadHere = (id: string) => linkFamilyThreadId(key, id); + const plural = (count: number) => (count === 1 ? "1 thread" : `${count} threads`); + const titles = (list: ReadonlyArray<{ readonly title: string }>) => + list.map((entry) => entry.title).join(", "); + return { + fromThread: (origin: NonNullable) => ({ + threadId: threadHere(origin.threadId), + requestId: ChildRequestId.make(derivedUuid("link-move-request", key, origin.requestId)), + kind: origin.kind, + }), + worktreeOrigin: + family.sharesCheckoutOf !== undefined + ? { kind: "thread" as const, threadId: threadHere(family.sharesCheckoutOf) } + : undefined, + /** The parent a child lands under, or why it lands as its own thread. */ + lineage: (projectId: string) => + Effect.gen(function* () { + if (family.parentThreadId === undefined) return null; + const parentId = threadHere(family.parentThreadId); + const found = yield* threadRows + .getById({ threadId: parentId }) + .pipe( + Effect.mapError( + () => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` }), + ), + ); + const parent = Option.getOrUndefined(found); + const own = (why: string): FamilyLanding => ({ + left: `${why}, so this is its own thread.`, + }); + if (parent === undefined || parent.deletedAt !== null) { + return own("The thread that started it isn't on this computer anymore"); + } + if ((parent.move ?? null) !== null || (parent.pendingMove ?? null) !== null) { + return own("The thread that started it is moving on from this computer"); + } + if (parent.projectId !== projectId) { + return own("The thread that started it is in another project here"); + } + return { + lineage: { + parentThreadId: parentId, + parentTurnId: + family.parentTurnId !== undefined + ? linkMoveTurnId(row, family.parentThreadId, family.parentTurnId) + : null, + }, + } satisfies FamilyLanding; + }), + /** The "Moved here" words for what of its family didn't come. */ + left: (fromLabel: string, lineageLeft: string | null) => { + const words: string[] = []; + if (lineageLeft !== null) words.push(lineageLeft); + const stayed = family.stayed ?? []; + if (stayed.length > 0) { + words.push( + `${plural(stayed.length)} it started stayed on ${fromLabel}: ${titles(stayed)}.`, + ); + } + const byComputer = new Map>(); + for (const entry of family.remoteStayed ?? []) { + byComputer.set(entry.label, [...(byComputer.get(entry.label) ?? []), entry]); + } + for (const [label, list] of byComputer) { + words.push( + `${plural(list.length)} it started on ${label} stayed there: ${titles(list)}. It can't reach ${list.length === 1 ? "it" : "them"} from here.`, + ); + } + const stopped = family.childRequestsStopped ?? 0; + if (stopped > 0) { + words.push( + `It was waiting on ${plural(stopped)} it started. ${stopped === 1 ? "It was" : "They were"} stopped for the move.`, + ); + } + return words; + }, + }; + }; + + /** + * The thread itself, and with it the commit. Waits for the engine's answer + * without letting go. A family member in another's folder (docs/design/ + * fleet.md, Part 3f, (g)) takes the folder that member's move made here, + * when that move is still coming. It holds only its own lock: no import + * ever waits for a second one, so none can wait on each other. The folder + * stays because the owner's clean-up leaves it while a member still coming + * shares it (cleanUp), and once this thread is in it. + */ + const commitStage = (row: LinkMoveRow) => { + const ownerId = row.manifest.family?.sharesCheckoutOf; + const key = row.familyKey; + if (ownerId === undefined || key === null) return commitThread(row); + return Effect.gen(function* () { + const owner = yield* moves + .findFamilyMember(key, ownerId) + .pipe(Effect.mapError(() => peerFailure(`${ownLabel()} couldn't read its moves.`))); + if ( + Option.isNone(owner) || + owner.value.status === "aborted" || + owner.value.manifest.family?.sharesCheckoutOf !== undefined || + !folderMade(owner.value) || + owner.value.worktreePath === null || + owner.value.branch === null + ) { + return yield* stop(OWNER_DIDNT_MOVE); + } + return yield* commitThread({ + ...row, + worktreePath: owner.value.worktreePath, + branch: owner.value.branch, + }); + }); + }; + + /** commitStage's work, for a row whose folder is known (its own, or the one it shares). */ + const commitThread = (row: LinkMoveRow) => Effect.gen(function* () { const land = yield* landing(row.manifest); if (land === null) return yield* stop(`${ownLabel()} doesn't have this project anymore.`); @@ -1940,8 +2320,12 @@ const make = Effect.gen(function* () { ); const attachments = yield* importAttachments(row); const key = row.transferKey; + // A family member's turns and messages are named from its family's key + // and its own thread there (linkMoveMessageId), so its relatives' + // records here name its turns alike and no two members share an id. + const family = familyOf(row); const messages = row.manifest.thread.messages.map((message): ThreadImportMessage => ({ - messageId: MessageId.make(derivedUuid("link-move-message", key, message.messageId)), + messageId: linkMoveMessageId(row, message.messageId), role: message.role, text: message.text, ...(message.attachments !== undefined @@ -1954,7 +2338,7 @@ const make = Effect.gen(function* () { turnId: message.turnId === null ? null - : TurnId.make(derivedUuid("link-move-turn", key, message.turnId)), + : linkMoveTurnId(row, row.manifest.source.threadId, message.turnId), ...(message.completesTurn !== undefined ? { completesTurn: message.completesTurn } : {}), ...(message.agentModels !== undefined ? { agentModels: message.agentModels } : {}), ...(message.sentFrom !== undefined ? { sentFrom: message.sentFrom } : {}), @@ -1967,6 +2351,10 @@ const make = Effect.gen(function* () { ...(message.requestKind !== undefined ? { requestKind: message.requestKind } : {}), ...(message.requestOutcome !== undefined ? { requestOutcome: message.requestOutcome } : {}), ...(message.requestError !== undefined ? { requestError: message.requestError } : {}), + // Between members of its family only, named as they are here. + ...(message.fromThread !== undefined && family !== null + ? { fromThread: family.fromThread(message.fromThread) } + : {}), createdAt: message.createdAt, })); const device = yield* devices @@ -2017,7 +2405,7 @@ const make = Effect.gen(function* () { resolved: roomResolved, carried: carriedRoom, hasDriver: (driver) => drivers.has(driver), - messageIdHere: (id) => MessageId.make(derivedUuid("link-move-message", key, id)), + messageIdHere: (id) => linkMoveMessageId(row, id), }); // How far the thread's own agent's carried session got, in a room. const ownSeen = row.manifest.thread.room?.ownAgentSeenThroughMessageId; @@ -2053,15 +2441,29 @@ const make = Effect.gen(function* () { now, room, }); - // The "Moved here" line's room words first, then what the thread had going. + // A child lands under its parent here, when the parent landed and is + // still here (Part 3f, (g)); otherwise as its own thread, with why. + const lineage = family === null ? null : yield* family.lineage(land.project.id); + const familyLeft = family === null ? [] : family.left(fromLabel, lineage?.left ?? null); + // The "Moved here" line's room words first, then its family's, then + // what the thread had going. const arrival = - stateArrival === undefined && room.brought.length === 0 && room.left.length === 0 + stateArrival === undefined && + room.brought.length === 0 && + room.left.length === 0 && + familyLeft.length === 0 ? undefined : { ...(stateArrival?.message !== undefined ? { message: stateArrival.message } : {}), brought: [...room.brought, ...(stateArrival?.brought ?? [])], - left: [...room.left, ...(stateArrival?.left ?? [])], + left: [...room.left, ...familyLeft, ...(stateArrival?.left ?? [])], }; + // Every message id it brings is its own: one another thread here holds + // would be moved into this one (messages are kept by id alone). The + // decider checks the recent ones too; this reads them all. + if (yield* messageIdsTaken(row.threadId, [...roomMessages, ...notSent])) { + return yield* stop(`${ownLabel()} already has one of its messages in another thread.`); + } const dispatched = yield* engine .dispatch({ type: "thread.import", @@ -2081,13 +2483,18 @@ const make = Effect.gen(function* () { threadId: row.manifest.source.threadId, movedAt: now, ...(carried && ownSeen !== undefined - ? { seenThrough: MessageId.make(derivedUuid("link-move-message", key, ownSeen)) } + ? { seenThrough: linkMoveMessageId(row, ownSeen) } : {}), ...(pullRequestSwitches !== undefined ? { pullRequestSwitches } : {}), + ...(row.familyKey !== null ? { familyKey: row.familyKey } : {}), }, // Queued messages for a room agent that didn't come: in the chat, never sent. messages: [...roomMessages, ...notSent], activities, + ...(lineage?.lineage !== undefined ? { lineage: lineage.lineage } : {}), + ...(family?.worktreeOrigin !== undefined + ? { worktreeOrigin: family.worktreeOrigin } + : {}), ...(carried ? { nativeSession: "carried" as const } : {}), ...(room.participants.length > 0 ? { participants: room.participants } : {}), ...(room.agentRole !== undefined ? { agentRole: room.agentRole } : {}), @@ -2386,7 +2793,7 @@ const make = Effect.gen(function* () { } // (f) Plans, with this computer's ids. - const key2 = (id: string) => derivedUuid("link-move-turn", key, id); + const key2 = (id: string) => linkMoveTurnId(row, row.manifest.source.threadId, id); const proposedPlans: OrchestrationProposedPlan[] = (state.proposedPlans ?? []).map( (plan) => ({ id: derivedUuid("link-move-plan", key, plan.id), @@ -2561,16 +2968,34 @@ const make = Effect.gen(function* () { */ const runImport = (linkDeviceId: string, transferId: string): Effect.Effect => { const key = linkMoveKey(linkDeviceId, transferId); - if (importing.has(key)) return Effect.void; + // One that is ending (a family member that just let its slot go) runs + // once more after it ends, so a start asked meanwhile is never lost. + if (importing.has(key)) { + importAgain.add(key); + return Effect.void; + } importing.add(key); const steps = Effect.gen(function* () { for (;;) { const next = yield* stage(linkDeviceId, transferId, (row) => Effect.gen(function* () { + // A family member waiting for a relative (Part 3f, (g)) lets its + // slot go; startImports picks it up again once it may go on. + const gate = yield* familyGate(row); + if (gate.kind === "stop") return yield* stop(gate.reason); + if (gate.kind === "wait") { + yield* setStage(row, { status: "waiting_for_family" }); + return true; + } switch (row.stage) { case null: - // A general chat has a folder of its own, not a checkout. - yield* isScratchMoveManifest(row.manifest) ? folderStage(row) : fetchStage(row); + // A general chat has a folder of its own, not a checkout; a + // family member in another's folder takes that one. + yield* isScratchMoveManifest(row.manifest) + ? folderStage(row) + : row.manifest.family?.sharesCheckoutOf !== undefined + ? sharerStage(row) + : fetchStage(row); return false; case "fetched": yield* worktreeStage(row); @@ -2606,7 +3031,14 @@ const make = Effect.gen(function* () { Effect.catchCause((cause) => Effect.logWarning("link move import failed", { transferId, cause }), ), - Effect.ensuring(Effect.sync(() => importing.delete(key))), + Effect.ensuring( + Effect.suspend(() => { + importing.delete(key); + return importAgain.delete(key) + ? runImport(linkDeviceId, transferId).pipe(Effect.forkIn(scope), Effect.asVoid) + : Effect.void; + }), + ), // Its slot is free: an allowed move waiting for one goes next. Effect.ensuring(Effect.suspend(() => startImports)), ); @@ -2619,12 +3051,23 @@ const make = Effect.gen(function* () { * admission lock, as offers are, so the two never overrun the caps together. */ const startImports: Effect.Effect = Effect.gen(function* () { + const dropped: Array<{ readonly row: LinkMoveRow; readonly reason: string }> = []; const started = yield* lock("admission")( Effect.gen(function* () { const open = yield* moves.listOpen; const inFlight = open.filter((entry) => !holdsNoSlot(entry)); const begun: Array = []; - for (const row of open.filter(waitingToImport)) { + // Family members whose relative is here now go on first (they are + // furthest along); one whose relative was dropped ends. + const ready: Array = []; + for (const row of open.filter((entry) => entry.status === "waiting_for_family")) { + const gate = yield* familyGate(row).pipe( + Effect.orElseSucceed(() => ({ kind: "wait" }) as const), + ); + if (gate.kind === "stop") dropped.push({ row, reason: gate.reason }); + else if (gate.kind === "ready") ready.push(row); + } + for (const row of [...ready, ...open.filter(waitingToImport)]) { const fromLink = inFlight.filter((entry) => entry.linkDeviceId === row.linkDeviceId); if (fromLink.length >= MAX_OPEN_MOVES_PER_LINK || inFlight.length >= MAX_OPEN_MOVES) { continue; @@ -2653,6 +3096,16 @@ const make = Effect.gen(function* () { for (const row of started) { yield* runImport(row.linkDeviceId, row.transferId).pipe(Effect.forkIn(scope)); } + for (const { row, reason } of dropped) { + yield* abortMove(row.linkDeviceId, row.transferId, reason).pipe( + Effect.catch((error) => + Effect.logWarning("link move waiting for its family couldn't be dropped", { + detail: error.message, + }), + ), + Effect.forkIn(scope), + ); + } }); // --------------------------------------------------------------------------- @@ -2818,13 +3271,20 @@ const make = Effect.gen(function* () { } else { yield* runImport(row.linkDeviceId, row.transferId).pipe(Effect.forkIn(scope)); } - } else if (!waitingToImport(row) && Date.parse(row.updatedAt) + LINK_MOVE_TTL_MS < now) { + } else if ( + !waitingToImport(row) && + Date.parse(row.updatedAt) + + (row.status === "waiting_for_family" ? LINK_MOVE_FAMILY_TTL_MS : LINK_MOVE_TTL_MS) < + now + ) { yield* abortMove( row.linkDeviceId, row.transferId, row.status === "awaiting_approval" ? `Nobody on ${ownLabel()} allowed the move in time.` - : "The move stopped arriving.", + : row.status === "waiting_for_family" + ? "The rest of its family never arrived." + : "The move stopped arriving.", row.status === "awaiting_approval" ? "expired" : undefined, ); } diff --git a/apps/server/src/links/RemoteChildReactor.test.ts b/apps/server/src/links/RemoteChildReactor.test.ts index 5f39c737f..87a05653c 100644 --- a/apps/server/src/links/RemoteChildReactor.test.ts +++ b/apps/server/src/links/RemoteChildReactor.test.ts @@ -304,7 +304,7 @@ const makeComputer = Effect.gen(function* () { .pipe(Effect.map((row) => Option.getOrThrow(row))); const callsTo = (method: string) => calls.filter((call) => call.method === method); - return { engine, snapshots, askForThread, recordRemote, boot, stored, callsTo }; + return { engine, snapshots, threadRows, askForThread, recordRemote, boot, stored, callsTo }; }); const report = (patch: Partial>): PeerWatchEvent => ({ @@ -660,4 +660,62 @@ it.layer(NodeServices.layer)("RemoteChildReactor", (it) => { }); }), ); + + it.effect( + "a parent frozen for its move takes no answer and acks no report, while the cancels it owes still go", + () => + Effect.gen(function* () { + const computer = yield* makeComputer; + yield* computer.askForThread; + yield* computer.recordRemote("running", { status: "accepted", threadId: REMOTE_CHILD }); + // The parent reads as frozen for its move (docs/design/fleet.md, Part + // 3f, (g)), a request still open on it. + const frozen = { + move: { + transferId: "transfer-1", + target: { environmentId: EnvironmentId.make("env-other"), label: "Other" }, + agent: MODEL, + phase: "exporting", + cancelRequested: false, + startedAt: AT, + }, + }; + const asFrozen = { + getById: (input: { readonly threadId: ThreadId }) => + computer.threadRows + .getById(input) + .pipe(Effect.map(Option.map((row) => ({ ...row, ...frozen }) as typeof row))), + }; + yield* computer.boot({ watch: [report({}), { type: "synced" }] }, { threadRows: asFrozen }); + yield* eventually( + Effect.sync(() => computer.callsTo("peer.watch").length > 0), + "the watch opens", + ); + yield* wallClockSleep(300); + // Its answer would be refused there and lost: it stays with that computer. + assert.deepEqual(computer.callsTo("peer.report.ack"), []); + assert.lengthOf((yield* computer.stored).childRequests?.open ?? [], 1); + + // Stop (as the move's "Stop and move now" does) owes that computer a + // cancel: it still goes out from a frozen parent. + yield* computer.engine.dispatch({ + type: "thread.session.stop", + commandId: CommandId.make("parent-stop"), + threadId: PARENT, + createdAt: AT, + }); + yield* computer.boot({}, { threadRows: asFrozen }); + yield* eventually( + Effect.sync(() => computer.callsTo("peer.request.cancel").length > 0), + "the cancel goes out", + ); + yield* eventually( + Effect.map( + computer.stored, + (parent) => (parent.childRequests?.remoteCancels ?? []).length === 0, + ), + "the cancel is recorded as delivered", + ); + }), + ); }); diff --git a/apps/server/src/links/RemoteChildReactor.ts b/apps/server/src/links/RemoteChildReactor.ts index 654ffcc8c..529dd01bc 100644 --- a/apps/server/src/links/RemoteChildReactor.ts +++ b/apps/server/src/links/RemoteChildReactor.ts @@ -72,6 +72,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; import { childReportMessageId } from "../orchestration/childThreadDecisions.ts"; +import { familyWorkStopped } from "../orchestration/threadMoveCarry.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts"; import { ComputerLinkClient, type ComputerLinkUnavailableError } from "./ComputerLinkClient.ts"; @@ -97,14 +98,19 @@ export class RemoteChildReactor extends Context.Service< const nowIso = Effect.map(DateTime.now, DateTime.formatIso); /** What the reactor needs of a parent, read from its stored row. */ -type Parent = Pick & { - readonly archivedAt: string | null; - readonly deletedAt: string | null; -}; +type Parent = Pick & + Pick & { + readonly archivedAt: string | null; + readonly deletedAt: string | null; + }; -/** Its children there, while it still shows them: neither archived nor deleted. */ +/** + * Its children there, while it still shows them: neither archived nor + * deleted, nor stopped for its move (familyWorkStopped, docs/design/fleet.md, + * Part 3f, (g)): a parent that moved away no longer knows them. + */ const childrenFollowed = (parent: Parent, environmentId: string) => - parent.deletedAt !== null || parent.archivedAt !== null + parent.deletedAt !== null || parent.archivedAt !== null || familyWorkStopped(parent) ? [] : (parent.childRequests.remoteChildren ?? []).filter( (child) => child.environmentId === environmentId, @@ -239,6 +245,8 @@ const make = Effect.gen(function* () { title: found.value.title, participants: found.value.participants ?? [], childRequests: found.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, + move: found.value.move ?? null, + pendingMove: found.value.pendingMove ?? null, archivedAt: found.value.archivedAt, deletedAt: found.value.deletedAt, }, @@ -522,7 +530,8 @@ const make = Effect.gen(function* () { return; case "status": { const found = yield* findRequest(environmentId, event.requestId); - if (found === undefined) return; + // A parent whose move stopped its agent is written nothing. + if (found === undefined || familyWorkStopped(found.parent)) return; const { parent, request } = found; if (event.status === "awaiting_approval") { yield* updateRequest(parent, request, { @@ -550,6 +559,7 @@ const make = Effect.gen(function* () { } case "thread": { for (const parent of yield* parentsHolding(environmentId, event.threadId)) { + if (familyWorkStopped(parent)) continue; const existing = remoteChildOf(parent.childRequests, event.threadId); if (existing === undefined || existing.environmentId !== environmentId) continue; const filing = event.filing ?? existing.filing; @@ -583,6 +593,10 @@ const make = Effect.gen(function* () { } case "report": { const found = yield* findRequest(environmentId, event.requestId); + // A parent whose move stopped its agent can't take the answer (it + // would refuse it, and a refusal reads as settled meanwhile): the + // report stays unacked there and comes again with a later watch. + if (found !== undefined && familyWorkStopped(found.parent)) return; if (found !== undefined) { const { parent, request } = found; const silent = @@ -687,7 +701,7 @@ const make = Effect.gen(function* () { Effect.gen(function* () { pendingAcks.delete(environmentId); for (const parent of yield* parentsOwing(environmentId)) { - for (const request of openRemote(parent, environmentId)) { + for (const request of familyWorkStopped(parent) ? [] : openRemote(parent, environmentId)) { if (request.remote === undefined) continue; yield* settleRequest(parent, request, { outcome: "failed", @@ -867,6 +881,8 @@ const make = Effect.gen(function* () { laneOf(requestLanes, environmentId).withPermits(1)( Effect.gen(function* () { const owed = (yield* parentsOwing(environmentId)) + // A parent whose move stopped its agent asks nothing new there. + .filter((parent) => !familyWorkStopped(parent)) .flatMap((parent) => openRemote(parent, environmentId) .filter( diff --git a/apps/server/src/links/peerRoute.ts b/apps/server/src/links/peerRoute.ts index 653aa57c0..b8de82f9a 100644 --- a/apps/server/src/links/peerRoute.ts +++ b/apps/server/src/links/peerRoute.ts @@ -224,6 +224,7 @@ export const makePeerRpcLayer = (input: { moveGeneralChats: true, moveRooms: true, moveOutsideWork: true, + moveFamilies: true, threadFiling: true, outsideAgents: true, } satisfies PeerDescriptor; diff --git a/apps/server/src/moves/MoveQueue.test.ts b/apps/server/src/moves/MoveQueue.test.ts index ce1083f77..317da0a1f 100644 --- a/apps/server/src/moves/MoveQueue.test.ts +++ b/apps/server/src/moves/MoveQueue.test.ts @@ -76,6 +76,8 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) { /** What the target answers before the stop, asked whether it takes what the thread carries. */ carryAnswer: { kind: "ok" } as Effect.Success>, carryChecks: 0, + /** How long checking a child that moves with its parent takes (a target that answers slowly). */ + childCheckMs: 0, }; const dispatch = (command: OrchestrationCommand): Effect.Effect => @@ -189,7 +191,10 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) { .map((thread) => thread.id), ), setsCheckBacks: () => Effect.succeed(true), - checkQueue: () => Effect.sync(() => ({ label: "Mac mini", takes: state.takes })), + checkQueue: (input) => + Effect.sleep( + Duration.millis(input.family?.parentThreadId !== undefined ? state.childCheckMs : 0), + ).pipe(Effect.as({ label: "Mac mini", takes: state.takes })), checkCarry: () => Effect.sync(() => { state.carryChecks += 1; @@ -871,3 +876,152 @@ describe("MoveQueue, a put-back a restart cut short (Part 3e)", () => { await h.close(); }); }); + +describe("MoveQueue, a family (Part 3f, (g))", () => { + const CHILD = ThreadId.make("thread-child"); + const OTHER = ThreadId.make("thread-other-child"); + const addWorkingChild = async (h: Awaited>, id: ThreadId) => { + await h.dispatch({ + type: "thread.create", + commandId: nextCommandId(), + threadId: id, + projectId: PROJECT, + title: id === CHILD ? "Fix tests" : "Review", + modelSelection: agent, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${id}`, + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand); + // At work, so its own queued move waits rather than starting at once. + await h.dispatch({ + type: "thread.session.set", + commandId: nextCommandId(), + threadId: id, + session: { + threadId: id, + status: "running", + providerName: "codex", + runtimeMode: "auto", + activeTurnId: TurnId.make(`turn-${id}`), + lastError: null, + updatedAt: now, + }, + createdAt: now, + } as OrchestrationCommand); + }; + const family = async () => { + const h = await harness(); + h.state.takes = { threadState: true, families: true }; + await h.startReactor(); + await addWorkingChild(h, CHILD); + await addWorkingChild(h, OTHER); + await h.setSession("running", { activeTurnId: TURN }); + const of = (id: ThreadId) => h.model().threads.find((entry) => entry.id === id)!; + return { h, of }; + }; + + it("an older app's move takes the whole family; a parent's move that ends ends its children's", async () => { + const { h, of } = await family(); + const { requestId } = await h.queueMove(); + const id = h.thread().pendingMove?.family?.id; + expect(h.thread().pendingMove?.family).toEqual({ id }); + for (const child of [CHILD, OTHER]) { + expect(of(child).pendingMove?.family).toEqual({ id, parentThreadId: THREAD }); + } + await h.run(h.queue.unqueue({ threadId: THREAD, requestId })); + await waitFor( + () => [CHILD, OTHER].every((child) => (of(child).pendingMove ?? null) === null), + "its children's moves to end", + ); + expect(of(CHILD).lastMoveOutcome).toMatchObject({ + result: "not_moved", + words: "Its parent thread didn't move.", + }); + // Its parent didn't move: it stays its child. + expect(of(CHILD).attachedToParent).toBe(true); + await h.close(); + }); + + it("a current app moves exactly the threads it lists, each parent before its children", async () => { + const { h, of } = await family(); + await h.run( + h.queue.queue({ + threadId: THREAD, + targetEnvironmentId: MAC_MINI, + agent, + mode: "when-done", + familySelection: "explicit", + children: [CHILD], + }), + ); + expect(of(CHILD).pendingMove?.family?.parentThreadId).toBe(THREAD); + expect(of(OTHER).pendingMove ?? null).toBeNull(); + await h.run( + h.queue.unqueue({ threadId: THREAD, requestId: h.thread().pendingMove!.requestId }), + ); + await waitFor(() => (of(CHILD).pendingMove ?? null) === null, "the child's move to end"); + + const result = await h.run( + h.queue.queueMany({ + threadIds: [OTHER, THREAD], + targetEnvironmentId: MAC_MINI, + mode: "when-done", + familySelection: "explicit", + }), + ); + expect(result.queued.map((entry) => entry.threadId)).toEqual([THREAD, OTHER]); + expect(of(OTHER).pendingMove?.family?.parentThreadId).toBe(THREAD); + expect(of(CHILD).pendingMove ?? null).toBeNull(); + // A child listed without its parent moves on its own: not yet. + await h.run( + h.queue.queueMany({ + threadIds: [CHILD], + targetEnvironmentId: MAC_MINI, + mode: "when-done", + familySelection: "explicit", + }), + ); + expect(of(CHILD).pendingMove ?? null).toBeNull(); + await h.close(); + }); + + it("queues a family in one go: no member starts before every member is queued", async () => { + const h = await harness(); + h.state.takes = { threadState: true, families: true }; + // Its children are checked slowly; everyone is idle, so a move starts at once. + h.state.childCheckMs = 200; + await h.startReactor(); + for (const id of [CHILD, OTHER]) { + await h.dispatch({ + type: "thread.create", + commandId: nextCommandId(), + threadId: id, + projectId: PROJECT, + title: id, + modelSelection: agent, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${id}`, + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand); + } + const of = (id: ThreadId) => h.model().threads.find((entry) => entry.id === id)!; + let queuedAtFirstStart: boolean | null = null; + h.state.beforeStart = async () => { + queuedAtFirstStart = [THREAD, CHILD, OTHER].every( + (id) => (of(id).pendingMove ?? null) !== null || (of(id).move ?? null) !== null, + ); + }; + await h.queueMove(); + await waitFor(() => queuedAtFirstStart !== null, "a move to start"); + expect(queuedAtFirstStart).toBe(true); + await h.close(); + }); +}); diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts index 4ee631a54..9b3dd5382 100644 --- a/apps/server/src/moves/MoveQueue.ts +++ b/apps/server/src/moves/MoveQueue.ts @@ -30,6 +30,8 @@ import { type ThreadMoveBatchMember, type ThreadMoveBatchStatus, ThreadMoveError, + type ThreadMoveFamily, + ThreadMoveFamilyId, type ThreadMoveHold, ThreadMoveRequestId, type ThreadMoveQueueInput, @@ -62,6 +64,7 @@ import { firstMoveBlock, isRestorePaid, moveWaitsOf, + PARENT_DIDNT_MOVE_WORDS, restoreMessageText, sameMoveStatus, type ThreadMoveRefusalEntry, @@ -238,14 +241,68 @@ const sessionMark = (thread: OrchestrationThread) => { : `${session.status}:${session.activeTurnId ?? ""}:${session.updatedAt}`; }; -/** A thread's move checks, from the thread alone: no other thread or project. */ +/** + * A thread's move checks, from the thread alone: no other thread or project. + * Whether a child's parent still moves needs the parent, so that one waits + * for the full look. + */ const localRefusals = (thread: OrchestrationThread) => threadMoveRefusals( { projects: [], threads: [thread] }, thread, // What the target said it takes, when the move was queued. thread.pendingMove?.targetTakes, - ); + ).filter((entry) => entry.code !== "child"); + +/** One thread a queue call moves, with the family it moves in (docs/design/fleet.md, Part 3f, (g)). */ +export interface PlannedMove { + readonly threadId: ThreadId; + readonly family?: ThreadMoveFamily; +} + +/** + * The threads a queue call moves, in order: each parent first with its + * family's id, then the children that come with it (all of them, or with + * `explicit` only those asked for), then the rest as asked. A child asked for + * without its parent moves on its own (its own check refuses that for now). + * `childrenOf` lists a thread's children here that could come. + */ +export const planFamilies = ( + asked: ReadonlyArray, + options: { + readonly explicit: boolean; + /** A single thread's call: its children asked for besides it. */ + readonly alsoAsked?: ReadonlyArray | undefined; + readonly childrenOf: (threadId: ThreadId) => Effect.Effect>; + readonly newFamilyId: () => ThreadMoveFamilyId; + }, +): Effect.Effect> => + Effect.gen(function* () { + const unique = [...new Set(asked)]; + const askedSet = new Set([...unique, ...(options.alsoAsked ?? [])]); + const coming = new Map>(); + for (const threadId of unique) { + const children = yield* options.childrenOf(threadId); + const picked = options.explicit ? children.filter((child) => askedSet.has(child)) : children; + if (picked.length > 0) coming.set(threadId, picked); + } + const withParent = new Set([...coming.values()].flat()); + const planned: PlannedMove[] = []; + for (const threadId of unique) { + if (withParent.has(threadId)) continue; + const children = coming.get(threadId); + if (children === undefined) { + planned.push({ threadId }); + continue; + } + const id = options.newFamilyId(); + planned.push({ threadId, family: { id } }); + for (const child of children) { + planned.push({ threadId: child, family: { id, parentThreadId: threadId } }); + } + } + return planned; + }); interface TrackedMove { requestId: ThreadMoveRequestId; @@ -456,8 +513,15 @@ export const makeMoveQueue = ( // A newer queued move than the one this was watching: watch it instead. yield* track(threadId, pending.requestId); const requestId = pending.requestId; - // From the thread alone first: while it works, nothing else needs reading. - if (yield* settleRefusals(threadId, pending, localRefusals(thread))) return; + // From the thread alone first: while it works, nothing else needs + // reading. A family's child always reads its parent: its move ends + // with the parent's, at work or not (Part 3f, (g)). + if ( + pending.family?.parentThreadId === undefined && + (yield* settleRefusals(threadId, pending, localRefusals(thread))) + ) { + return; + } const context = yield* deps.readContext(threadId); if (context === null) return yield* forget(threadId); const refusals = threadMoveRefusals( @@ -708,15 +772,30 @@ export const makeMoveQueue = ( // The service. // ------------------------------------------------------------------------- - /** Checks one move and records it as the thread's queued move: `queue`, and each of a batch. */ + /** + * Checks one move and records it as the thread's queued move: `queue`, and + * each of a batch. A parent's children that come with it (`children`, + * planFamilies) are checked first, each as if its parent were queued, and + * queued in the same decision as the parent (docs/design/fleet.md, Part + * 3f, (g)), so no member packs before every member is known. One refused + * stays here (`refusedChildren`, with why). + */ const queueOne = ( - input: ThreadMoveQueueInput & { readonly requestedBy?: ThreadMoveRequester }, + input: ThreadMoveQueueInput & { + readonly requestedBy?: ThreadMoveRequester; + /** The family it moves with (planFamilies). */ + readonly family?: ThreadMoveFamily | undefined; + }, batch?: { - readonly batchId: ThreadMoveBatchId; + readonly batchId?: ThreadMoveBatchId | undefined; readonly targets: ReadonlyArray; /** Recorded in the batch before it is queued. */ - readonly requestId: ThreadMoveRequestId; + readonly requestId?: ThreadMoveRequestId | undefined; }, + children: ReadonlyArray<{ + readonly threadId: ThreadId; + readonly requestId: ThreadMoveRequestId; + }> = [], ) => Effect.gen(function* () { const { label, takes } = yield* deps.checkQueue({ @@ -725,7 +804,26 @@ export const makeMoveQueue = ( agent: input.agent, roomAgents: input.roomAgents, targets: batch?.targets, + family: input.family, }); + const coming: Array<{ threadId: ThreadId; requestId: ThreadMoveRequestId }> = []; + const refusedChildren: Array<{ threadId: ThreadId; words: string }> = []; + const family = input.family; + if (family !== undefined) { + for (const child of children) { + const checked = yield* deps + .checkQueue({ + threadId: child.threadId, + targetEnvironmentId: input.targetEnvironmentId, + targets: batch?.targets, + family: { id: family.id, parentThreadId: input.threadId }, + withParent: true, + }) + .pipe(Effect.result); + if (checked._tag === "Success") coming.push(child); + else refusedChildren.push({ threadId: child.threadId, words: checked.failure.detail }); + } + } const requestId = batch?.requestId ?? ThreadMoveRequestId.make(randomUUID()); yield* deps .dispatch({ @@ -738,16 +836,77 @@ export const makeMoveQueue = ( ...(input.roomAgents !== undefined ? { roomAgents: input.roomAgents } : {}), mode: input.mode, requestedBy: input.requestedBy ?? { kind: "user" }, - ...(batch !== undefined ? { batchId: batch.batchId } : {}), + ...(batch?.batchId !== undefined ? { batchId: batch.batchId } : {}), targetTakes: takes, + ...(input.family !== undefined ? { family: input.family } : {}), + ...(coming.length > 0 ? { children: coming } : {}), createdAt: yield* nowIso, }) .pipe(Effect.mapError((error) => moveError(error.message))); - return { requestId, label }; + // A child its own checks refused in that decision (a race since its + // check) holds no queued move: it stays too. + for (const child of coming) { + const queuedNow = (yield* deps.readThread(child.threadId))?.pendingMove ?? null; + if (queuedNow?.requestId !== child.requestId) { + refusedChildren.push({ + threadId: child.threadId, + words: "It couldn't move with the thread that started it.", + }); + } + } + return { requestId, label, refusedChildren }; }); + /** A thread's children here that could move with it: attached, neither archived nor deleted. */ + const childrenOf = (threadId: ThreadId) => + deps + .readContext(threadId) + .pipe( + Effect.map((context) => + (context?.view.threads ?? []) + .filter( + (child) => + child.parentThreadId === threadId && + child.attachedToParent && + child.deletedAt === null && + child.archivedAt === null, + ) + .map((child) => child.id), + ), + ); + + const newFamilyId = () => ThreadMoveFamilyId.make(randomUUID()); + + /** + * One thread, and the children that come with it (docs/design/fleet.md, + * Part 3f, (g)): all of them unless the call says which (`explicit`). + * The thread is queued first; a child refused stays here, and becomes its + * own thread if the parent moves. + */ const queue: MoveQueueShape["queue"] = (input) => - queueOne(input).pipe(Effect.map(({ requestId }) => ({ requestId }))); + Effect.gen(function* () { + const planned = yield* planFamilies([input.threadId], { + explicit: input.familySelection === "explicit", + alsoAsked: input.children, + childrenOf, + newFamilyId, + }); + const [own, ...children] = planned; + // With children, the computers are asked once for all of them. + const targets = children.length > 0 ? yield* deps.describeTargets : undefined; + const { requestId, refusedChildren } = yield* queueOne( + { ...input, family: own?.family }, + targets !== undefined ? { targets } : undefined, + children.map((child) => ({ + threadId: child.threadId, + requestId: ThreadMoveRequestId.make(randomUUID()), + })), + ); + for (const child of refusedChildren) { + yield* Effect.logInfo("move queue: a thread stays behind its parent", child); + } + return { requestId }; + }); const unrecorded = () => moveError("The moves couldn't be recorded. Try again."); @@ -763,9 +922,16 @@ export const makeMoveQueue = ( onNone: () => described?.label ?? "the other computer", onSome: (peer) => peer.label, }); - const planned = threadIds.map((threadId) => ({ - threadId, + // Each parent with the children that come with it (Part 3f, (g)). + const families = yield* planFamilies(threadIds, { + explicit: input.familySelection === "explicit", + childrenOf, + newFamilyId, + }); + const planned = families.map((entry) => ({ + threadId: entry.threadId, requestId: ThreadMoveRequestId.make(randomUUID()), + ...(entry.family !== undefined ? { family: entry.family } : {}), })); const row: ThreadMoveBatchRow = { batchId, @@ -775,26 +941,47 @@ export const makeMoveQueue = ( // Each member's queued move is named before any is queued, so a // batch cut short (a crash, a failed write) still knows every move // it made; one never queued reads as not moved. - members: planned, + members: planned.map(({ threadId, requestId }) => ({ threadId, requestId })), refused: [], }; yield* deps.batches.upsert(row).pipe(Effect.mapError(unrecorded)); const queued: Array<{ threadId: ThreadId; requestId: ThreadMoveRequestId }> = []; const refused: Array<{ threadId: ThreadId; words: string }> = []; + // A parent and its children go in one decision; its children are + // queued (or refused) with it. + const plannedChildrenOf = (parentId: ThreadId) => + planned.filter((entry) => entry.family?.parentThreadId === parentId); for (const member of planned) { + if (member.family?.parentThreadId !== undefined) continue; const requestId = member.requestId; + const children = plannedChildrenOf(member.threadId); const one = yield* queueOne( { threadId: member.threadId, targetEnvironmentId: input.targetEnvironmentId, mode: input.mode, + family: member.family, }, { batchId, targets, requestId }, + children.map(({ threadId, requestId: childRequestId }) => ({ + threadId, + requestId: childRequestId, + })), ).pipe(Effect.result); if (one._tag === "Success") { queued.push({ threadId: member.threadId, requestId }); + const left = new Set(one.success.refusedChildren.map((entry) => entry.threadId)); + for (const child of children) { + if (!left.has(child.threadId)) { + queued.push({ threadId: child.threadId, requestId: child.requestId }); + } + } + refused.push(...one.success.refusedChildren); } else { refused.push({ threadId: member.threadId, words: one.failure.detail }); + for (const child of children) { + refused.push({ threadId: child.threadId, words: PARENT_DIDNT_MOVE_WORDS }); + } } } // The refusals' words; without them a refused member still reads as @@ -954,8 +1141,14 @@ export const makeMoveQueue = ( if (entry?.requestId === event.payload.requestId) { yield* forget(event.payload.threadId); } + // A parent's move that ended without starting ends its + // family's queued moves too (Part 3f, (g)): they look again. + if (event.payload.reason !== "started") yield* lookAtAll(settleDelay, false); return; } + if (event.type === "thread.move-aborted") { + yield* lookAtAll(settleDelay, false); + } // A move that didn't happen owes the thread what it took. if ( event.type === "thread.move-restore-set" && diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index d3f44af15..87f2f870f 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -358,6 +358,9 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { linkedPullRequests: [], participants: [], agentRequests: { open: [] }, + parentThreadId: null, + attachedToParent: false, + childRequests: { open: [] }, ...patch, }) as unknown as OrchestrationThread; const view = { projects: [{ id: "project-1", kind: "project" }] } as never; diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts index ef9faeb4c..07543f1ca 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -44,6 +44,7 @@ import { type ThreadMoveRoomAgentChoice, type ThreadMoveRoomAgentTarget, type ThreadMoveStartInput, + type ThreadMoveFamily, type ThreadMoveTakes, type ThreadMoveTargetPreview, } from "@threadlines/contracts"; @@ -75,11 +76,14 @@ import { } from "../orchestration/threadMoveCarry.ts"; import { firstMoveBlock, + holdsFamily, moveWaitsOf, threadMoveRefusal, threadMoveRefusals, + type ThreadMoveView, } from "../orchestration/threadMoveDecisions.ts"; import { ThreadActionGate } from "./ThreadActionGate.ts"; +import { familyManifestOf, familyThreadIdsOf } from "./familyMove.ts"; import { cantComeWords, movingRoomAgents, @@ -170,6 +174,13 @@ export interface ThreadMovesShape { readonly roomAgents?: ReadonlyArray | undefined; /** The computers as already described (a batch); absent: described now. */ readonly targets?: ReadonlyArray | undefined; + /** The family it moves with (ThreadMoveFamily), its parent queued already. */ + readonly family?: ThreadMoveFamily | undefined; + /** + * A child about to be queued in the same decision as its parent: checked + * as if its parent held the family's move already. + */ + readonly withParent?: boolean | undefined; }) => Effect.Effect< { readonly label: string; @@ -275,6 +286,7 @@ export function takesOf(peer: PeerDescriptor): ThreadMoveTakes { ...(peer.moveGeneralChats === true ? { generalChats: true as const } : {}), ...(peer.moveRooms === true ? { rooms: true as const } : {}), ...(peer.moveOutsideWork === true ? { outsideWork: true as const } : {}), + ...(peer.moveFamilies === true ? { families: true as const } : {}), }; } @@ -754,6 +766,15 @@ const make = Effect.gen(function* () { readonly withChanges?: boolean; /** Say what each agent would get of the thread's own session (the dialogs). */ readonly withSession?: boolean; + /** The family it is about to be queued with (its own queued move's when absent). */ + readonly family?: ThreadMoveFamily | undefined; + /** Say what its family does (the single thread's dialog). */ + readonly withFamily?: boolean; + /** + * Threads asked about with it (a batch): a child whose parent is one of + * them can go with it, so being a child is no refusal there. + */ + readonly askedWith?: ReadonlySet | undefined; } = {}, ) => Effect.gen(function* () { @@ -767,7 +788,13 @@ const make = Effect.gen(function* () { const project = view.projects.find((entry) => entry.id === thread.projectId); // As if the other computer took everything (docs/design/fleet.md, Part // 3e): one that doesn't says so as its own refusal. - const refusals = threadMoveRefusals(view, thread, ALL_MOVE_TAKES); + const withParent = + thread.parentThreadId !== null && + thread.attachedToParent && + options.askedWith?.has(thread.parentThreadId) === true; + const refusals = threadMoveRefusals(view, thread, ALL_MOVE_TAKES, options.family).filter( + (entry) => !(withParent && entry.code === "child"), + ); const carry = threadMoveCarry(view, thread); const pending = thread.pendingMove ?? null; let refusal: string | null = @@ -865,6 +892,7 @@ const make = Effect.gen(function* () { ); const waitsFor = moveWaitsOf(refusals); const brings = carryBringsWords(carry).map((words) => ({ words })); + const family = options.withFamily === true ? yield* familyPreviewOf(thread, view) : undefined; return { thread, carry, @@ -888,11 +916,72 @@ const make = Effect.gen(function* () { }, } : {}), + ...(family !== undefined ? { family } : {}), targets, } satisfies ThreadMovePreview, }; }); + /** + * A family as the move dialog shows it (docs/design/fleet.md, Part 3f, + * (g)): a parent's children here, each with why it can't come when it + * can't (then it stays as its own thread), and the threads its agent + * started on other computers, which stay there; a child's parent. None for + * a thread with neither. + */ + const familyPreviewOf = (thread: OrchestrationThread, view: ThreadMoveView) => + Effect.gen(function* () { + const parent = + thread.parentThreadId !== null && thread.attachedToParent + ? view.threads.find((entry) => entry.id === thread.parentThreadId) + : undefined; + const children = view.threads.filter( + (entry) => + entry.parentThreadId === thread.id && + entry.attachedToParent && + entry.deletedAt === null && + entry.archivedAt === null, + ); + const remoteChildren = (thread.childRequests.remoteChildren ?? []).map((entry) => ({ + label: entry.label, + title: entry.title, + })); + if (parent === undefined && children.length === 0 && remoteChildren.length === 0) { + return undefined; + } + // Each child's own checks, as if it came with this thread: its parent's + // move doesn't exist yet, so that check is left out. + const rows = yield* Effect.forEach(children, (child) => + readMoveContext(child.id).pipe( + Effect.map((context) => { + const refusal = + context === null + ? "This thread is gone." + : firstMoveBlock( + threadMoveRefusals(context.view, context.thread, ALL_MOVE_TAKES).filter( + (entry) => entry.code !== "child", + ), + )?.words; + return { + threadId: child.id, + title: child.title, + ...(refusal !== undefined ? { refusal } : {}), + }; + }), + Effect.orElseSucceed(() => ({ + threadId: child.id, + title: child.title, + refusal: "This thread couldn't be read.", + })), + ), + ); + return { + ...(parent !== undefined ? { parent: { threadId: parent.id, title: parent.title } } : {}), + children: rows, + remoteChildren, + } satisfies NonNullable; + }); + /** * Whether GitHub is signed in for the project on each computer that takes * thread state (`peer.move.readiness`); one that doesn't answer in time is @@ -932,16 +1021,24 @@ const make = Effect.gen(function* () { }; const preview: ThreadMovesShape["preview"] = (threadId) => - inspect(threadId, { withSession: true }).pipe(Effect.map((inspected) => inspected.preview)); + inspect(threadId, { withSession: true, withFamily: true }).pipe( + Effect.map((inspected) => inspected.preview), + ); const previewMany: ThreadMovesShape["previewMany"] = (threadIds) => Effect.gen(function* () { const described = yield* describeTargets; const targets = described.map((target) => targetPreviewOf(target, null)); + const askedWith = new Set(threadIds); const threads = yield* Effect.forEach( threadIds, (threadId) => - inspect(threadId, { targets: described, withChanges: false, withSession: true }).pipe( + inspect(threadId, { + targets: described, + withChanges: false, + withSession: true, + askedWith, + }).pipe( Effect.map(({ preview: shown }) => previewManyThread(threadId, shown, targets)), Effect.catch((error) => Effect.succeed({ threadId, refusal: error.detail })), ), @@ -1018,6 +1115,10 @@ const make = Effect.gen(function* () { const inspected = yield* inspect(input.threadId, { targets: input.targets, withChanges: false, + family: input.family, + ...(input.withParent === true && input.family?.parentThreadId !== undefined + ? { askedWith: new Set([input.family.parentThreadId]) } + : {}), }); const shown = inspected.preview; if (shown.refusal !== undefined) return yield* moveError(shown.refusal); @@ -1262,6 +1363,22 @@ const make = Effect.gen(function* () { for (;;) { const move = yield* currentMove(threadId, transferId); if (move === null) return null; + // A member whose parent's move, or whose folder's owner's move, ended + // without landing there (Part 3f, (g)) is dropped there too: the + // other computer never lands it without them, and would otherwise + // wait out its expiry. + if (!move.cancelRequested && (yield* familyRelativeGone(transferId, move.family))) { + yield* engine + .dispatch({ + type: "thread.move.cancel", + commandId: CommandId.make(`server:thread-move:${transferId}:family-cancel`), + threadId, + transferId, + createdAt: yield* nowIso, + }) + .pipe(Effect.ignore); + continue; + } if (move.cancelRequested) { return yield* peerCall(threadId, environmentId, (peer) => peer["peer.move.abort"]({ transferId }), @@ -1276,6 +1393,31 @@ const make = Effect.gen(function* () { } }); + /** + * Whether a family member's move can no longer land there (docs/design/ + * fleet.md, Part 3f, (g)): a relative it waits for there (its parent, or + * the member whose folder it shares, as its packed manifest names it) no + * longer holds a move of the family here, or is gone. The other computer + * would wait for it until its own expiry. False for a thread that moves on + * its own, and while a relative can't be read. + */ + const familyRelativeGone = (transferId: ThreadMoveId, family: ThreadMoveFamily | undefined) => + Effect.gen(function* () { + if (family === undefined) return false; + const relatives: ThreadId[] = []; + if (family.parentThreadId !== undefined) relatives.push(family.parentThreadId); + const packed = yield* readMoveExport(moveDir(transferId)); + const manifest = + packed === null ? Option.none() : yield* decodeManifest(packed).pipe(Effect.option); + const owner = Option.isSome(manifest) ? manifest.value.family?.sharesCheckoutOf : undefined; + if (owner !== undefined && owner !== family.parentThreadId) relatives.push(owner); + for (const threadId of relatives) { + const row = yield* threadRows.getById({ threadId }).pipe(Effect.orElseSucceed(() => null)); + if (row !== null && !holdsFamily(Option.getOrUndefined(row), family)) return true; + } + return false; + }); + /** moveAbortCode for a move as it stands now. */ const abortCodeOf = (threadId: ThreadId, transferId: ThreadMoveId, state: PeerMoveState) => currentMove(threadId, transferId).pipe( @@ -1374,6 +1516,17 @@ const make = Effect.gen(function* () { ? yield* roomExportOf(detail.value, targetEnvironmentId) : undefined; const outsideWork = takes?.outsideWork === true ? (detail.value.outsideWork ?? []) : []; + // Its family (Part 3f, (g)), only for a computer that takes families. + const moveFamily = takes?.families === true ? detail.value.move?.family : undefined; + const threads = model.threads.map((entry) => + entry.id === detail.value.id ? detail.value : entry, + ); + const family = + moveFamily === undefined + ? undefined + : familyManifestOf({ projects: model.projects, threads }, detail.value, moveFamily); + const familyThreadIds = + moveFamily === undefined ? undefined : familyThreadIdsOf(threads, moveFamily); const source = { environmentId: descriptor.environmentId, environmentLabel: environment.currentLabel(), @@ -1391,6 +1544,8 @@ const make = Effect.gen(function* () { state, room, outsideWork, + family, + familyThreadIds, }); } const { place, checkout } = yield* whereFrom(detail.value, project.workspaceRoot); @@ -1398,6 +1553,8 @@ const make = Effect.gen(function* () { state, room, outsideWork, + family, + familyThreadIds, git, checkout, transferId, diff --git a/apps/server/src/moves/familyMove.ts b/apps/server/src/moves/familyMove.ts new file mode 100644 index 000000000..c3ea3648b --- /dev/null +++ b/apps/server/src/moves/familyMove.ts @@ -0,0 +1,104 @@ +/** + * A family when it moves (docs/design/fleet.md, Part 3f, (g)), on the + * computer it leaves: which threads move in it, which of them owns a folder + * several work in (only the owner sends its files; the others share the + * folder that owner's move makes there), and what a member's manifest says + * of its family. Pure: ThreadMoves reads the threads and asks these. + */ +import type { + OrchestrationThread, + PeerMoveFamily, + ThreadMoveFamily, + ThreadMoveFamilyId, +} from "@threadlines/contracts"; +import { PEER_MOVE_FAMILY_MAX_STAYED } from "@threadlines/contracts"; + +import { checkoutOf, type ThreadMoveView } from "../orchestration/threadMoveDecisions.ts"; + +/** The threads here that move in `familyId`: each whose queued move or move names it. */ +export const familyMembersOf = ( + threads: ReadonlyArray, + familyId: ThreadMoveFamilyId, +): ReadonlyArray => + threads.filter( + (thread) => + thread.deletedAt === null && + (thread.pendingMove?.family?.id === familyId || thread.move?.family?.id === familyId), + ); + +/** + * The member that owns a folder several members work in, and so sends its + * files: the one whose worktree it is (no guest marker), else the parent, + * else the oldest. Every member decides this alike, from the same members. + */ +export function checkoutOwnerOf( + group: ReadonlyArray, +): OrchestrationThread | undefined { + const owners = group.filter((thread) => (thread.worktreeOrigin ?? null) === null); + const pool = owners.length > 0 ? owners : group; + const parent = pool.find( + (thread) => (thread.pendingMove?.family ?? thread.move?.family)?.parentThreadId === undefined, + ); + if (parent !== undefined) return parent; + return pool.toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + )[0]; +} + +/** + * What `thread`'s manifest says of its family: the family's id, its parent + * and the parent's turn that started it (a child), the member whose folder + * it shares there (one that doesn't own the folder it works in), and, on the + * parent, the children that stay here, the ones its agent started on other + * computers (they stay there), and the waits its move's stop ended. + */ +export function familyManifestOf( + view: Pick, + thread: OrchestrationThread, + family: ThreadMoveFamily, +): PeerMoveFamily { + const members = familyMembersOf(view.threads, family.id); + const memberIds = new Set(members.map((member) => member.id)); + const checkout = checkoutOf(view, thread); + const group = members.filter((member) => checkoutOf(view, member) === checkout); + const owner = checkout === null ? undefined : checkoutOwnerOf(group); + const isParent = family.parentThreadId === undefined; + const stayed = isParent + ? view.threads + .filter( + (child) => + child.parentThreadId === thread.id && + child.attachedToParent && + child.deletedAt === null && + child.archivedAt === null && + !memberIds.has(child.id), + ) + .slice(0, PEER_MOVE_FAMILY_MAX_STAYED) + .map((child) => ({ title: child.title })) + : []; + const remoteStayed = isParent + ? (thread.childRequests.remoteChildren ?? []) + .slice(0, PEER_MOVE_FAMILY_MAX_STAYED) + .map((child) => ({ label: child.label, title: child.title })) + : []; + const stopped = thread.move?.interrupted?.childRequestsStopped; + return { + id: family.id, + ...(family.parentThreadId !== undefined ? { parentThreadId: family.parentThreadId } : {}), + ...(family.parentThreadId !== undefined && thread.parentTurnId !== null + ? { parentTurnId: thread.parentTurnId } + : {}), + ...(owner !== undefined && owner.id !== thread.id ? { sharesCheckoutOf: owner.id } : {}), + ...(stayed.length > 0 ? { stayed } : {}), + ...(remoteStayed.length > 0 ? { remoteStayed } : {}), + ...(isParent && stopped !== undefined ? { childRequestsStopped: stopped } : {}), + }; +} + +/** The threads a member's history may name as family (ThreadImportMessage.fromThread). */ +export const familyThreadIdsOf = ( + threads: ReadonlyArray, + family: ThreadMoveFamily, +): ReadonlySet => + new Set(familyMembersOf(threads, family.id).map((member) => member.id)); diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts index 891342dc3..8c51bd5ee 100644 --- a/apps/server/src/moves/moveExport.ts +++ b/apps/server/src/moves/moveExport.ts @@ -20,6 +20,7 @@ import type { OrchestrationOutsideWork, OrchestrationThread, OrchestrationThreadActivity, + PeerMoveFamily, PeerMoveGitManifest, PeerMoveManifest, PeerMovePart, @@ -292,7 +293,14 @@ interface PendingPart { */ export function exportThreadHistory( thread: OrchestrationThread, - options: { readonly room?: boolean } = {}, + options: { + readonly room?: boolean; + /** + * A family's members (Part 3f, (g)): a request or report between them + * keeps where it came from; one naming any other thread goes plain. + */ + readonly familyThreadIds?: ReadonlySet | undefined; + } = {}, ): { readonly messages: ReadonlyArray; readonly activities: ReadonlyArray; @@ -324,6 +332,7 @@ export function exportThreadHistory( ...(message.trigger !== undefined ? { trigger: message.trigger } : {}), ...(message.notSent === true || queuedIds.has(message.id) ? { notSent: true as const } : {}), ...(options.room === true ? roomFieldsOf(message) : {}), + ...familyFieldsOf(message, options.familyThreadIds), createdAt: message.createdAt, })); const activities = thread.activities @@ -344,6 +353,30 @@ export function exportThreadHistory( return { messages, activities }; } +/** + * Where a family's message came from (a request or report between members), + * as the move carries it: only between threads that move together on this + * computer, never a lead chat's pass or a thread on another computer. + */ +function familyFieldsOf( + message: OrchestrationThread["messages"][number], + familyThreadIds: ReadonlySet | undefined, +) { + const origin = message.fromThread; + if ( + familyThreadIds === undefined || + origin === undefined || + origin.environmentId !== undefined || + origin.ceiling !== undefined || + !familyThreadIds.has(origin.threadId) + ) { + return {}; + } + return { + fromThread: { threadId: origin.threadId, requestId: origin.requestId, kind: origin.kind }, + }; +} + /** A room message's own fields, as the move carries them. */ function roomFieldsOf(message: OrchestrationThread["messages"][number]) { return { @@ -458,6 +491,14 @@ export interface MoveExportInput { readonly room?: MoveRoomExport | undefined; /** The outside-work marks, for a computer that takes them. */ readonly outsideWork?: ReadonlyArray | undefined; + /** + * Its family (Part 3f, (g)), for a computer that takes families. With + * `sharesCheckoutOf`, the folder is another member's to send: this one + * carries none of its files. + */ + readonly family?: PeerMoveFamily | undefined; + /** The family's members here, whose requests and reports keep their origin. */ + readonly familyThreadIds?: ReadonlySet | undefined; } /** @@ -524,6 +565,7 @@ export function sha256OfFile(path: string) { export function writeMoveExport( input: MoveExportInput, ): Effect.Effect { + if (input.family?.sharesCheckoutOf !== undefined) return writeSharerExport(input); const { git, checkout, dir } = input; const root = checkout.root; const attempt = Effect.gen(function* () { @@ -634,7 +676,10 @@ export function writeMoveExport( return yield* fail(`${path} isn't a regular file, so it can't move.`); } } - const history = exportThreadHistory(input.thread, { room: input.room !== undefined }); + const history = exportThreadHistory(input.thread, { + room: input.room !== undefined, + familyThreadIds: input.familyThreadIds, + }); parts.push(...(yield* attachmentParts(history, input.attachmentsDir, input.state))); const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); if (otherBytes > MOVE_MAX_BYTES) { @@ -692,6 +737,7 @@ export function writeMoveExport( unpushedCommits: checkout.unpushedCommits, }, ...session.manifest, + ...(input.family !== undefined ? { family: input.family } : {}), }; yield* writeManifest(dir, manifest); return manifest; @@ -703,6 +749,83 @@ export function writeMoveExport( ); } +/** + * Packs a family member that works in another member's folder (docs/design/ + * fleet.md, Part 3f, (g)): its history, attachments, state and session, but + * none of the folder's files, which the folder's owner sends. The other + * computer puts it in the folder that owner's move makes. `git` says where + * the folder stands, for the record; with no commits of its own it names no + * base. + */ +function writeSharerExport( + input: MoveExportInput, +): Effect.Effect { + return Effect.gen(function* () { + yield* fsCall("Couldn't make room to pack this thread.", () => + NodeFs.mkdir(input.dir, { recursive: true }), + ); + const history = exportThreadHistory(input.thread, { + room: input.room !== undefined, + familyThreadIds: input.familyThreadIds, + }); + const parts = [...(yield* attachmentParts(history, input.attachmentsDir, input.state))]; + const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); + if (otherBytes > MOVE_MAX_BYTES) { + return yield* fail( + `This thread's attachments come to ${Math.ceil(otherBytes / (1024 * 1024))} MB. Moves carry at most 100 MB.`, + ); + } + const session = yield* sessionParts( + input.nativeSession ?? null, + input.room?.sessions ?? [], + otherBytes, + ); + parts.push(...session.parts); + const payload = yield* writePayload(input.dir, parts); + if (payload === null) { + return yield* fail("This thread's attachments changed while it was being packed. Try again."); + } + const checkout = input.checkout; + const manifest: PeerMoveGitManifest = { + totalBytes: payload.totalBytes, + sha256: payload.sha256, + parts: payload.table, + source: input.source, + project: { + canonicalKey: input.canonicalKey, + subdirectory: input.subdirectory, + title: input.projectTitle, + }, + git: { + headSha: checkout.headSha, + branch: checkout.branch, + baseSha: null, + ...(checkout.upstreamBranch !== null ? { upstreamBranch: checkout.upstreamBranch } : {}), + }, + thread: { + title: input.thread.title, + runtimeMode: input.thread.runtimeMode, + interactionMode: input.thread.interactionMode, + messages: history.messages, + activities: history.activities, + ...(input.state !== undefined ? { state: input.state } : {}), + ...roomManifestOf(input, session.room), + }, + agent: input.agent, + summary: { + messageCount: history.messages.length, + trackedFiles: 0, + untrackedFiles: 0, + unpushedCommits: 0, + }, + ...session.manifest, + ...(input.family !== undefined ? { family: input.family } : {}), + }; + yield* writeManifest(input.dir, manifest); + return manifest; + }); +} + /** * The attachments a move carries, one part each: its history's messages', and * its queued messages' (docs/design/fleet.md, Part 3e, (e)). A missing one @@ -1015,6 +1138,9 @@ export interface ScratchExportInput { readonly state?: PeerMoveThreadState | undefined; readonly room?: MoveRoomExport | undefined; readonly outsideWork?: ReadonlyArray | undefined; + /** Its family (Part 3f, (g)): a general chat has its own folder, so it shares none. */ + readonly family?: PeerMoveFamily | undefined; + readonly familyThreadIds?: ReadonlySet | undefined; } /** @@ -1088,7 +1214,10 @@ export function writeScratchExport( read: () => NodeFs.readFile(entry.absolute), }, ); - const history = exportThreadHistory(input.thread, { room: input.room !== undefined }); + const history = exportThreadHistory(input.thread, { + room: input.room !== undefined, + familyThreadIds: input.familyThreadIds, + }); parts.push(...(yield* attachmentParts(history, input.attachmentsDir, input.state))); const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); if (otherBytes > MOVE_MAX_BYTES) { @@ -1125,6 +1254,7 @@ export function writeScratchExport( agent: input.agent, summary: { messageCount: history.messages.length, files: before.length }, ...session.manifest, + ...(input.family !== undefined ? { family: input.family } : {}), }; yield* writeManifest(input.dir, manifest); return manifest; diff --git a/apps/server/src/moves/threadMoveView.ts b/apps/server/src/moves/threadMoveView.ts index 85d1f2cd3..278e18f3d 100644 --- a/apps/server/src/moves/threadMoveView.ts +++ b/apps/server/src/moves/threadMoveView.ts @@ -1,7 +1,8 @@ /** * What the move checks (threadMoveRefusals) read about one thread, and no * more: the thread, the threads that could hold its move (its attached - * children, and threads working in the same checkout), and their projects. + * children, its parent, and threads working in the same checkout), and their + * projects. * Loading the whole command read model for this costs about half a second * on an install with 3,000 threads; this costs a few milliseconds. */ @@ -44,7 +45,9 @@ export const makeThreadMoveContextReader = Effect.gen(function* () { project?.kind === "general-chat" ? null : (thread.worktreePath ?? project?.workspaceRoot ?? null); - // Its attached children, and every other thread in the same checkout. + // Its attached children, its parent (whose move a child's goes with, + // docs/design/fleet.md, Part 3f, (g)), and every other thread in the + // same checkout. const neighbors = yield* sql<{ readonly threadId: ThreadId }>` SELECT t.thread_id AS "threadId" FROM projection_threads t @@ -53,6 +56,7 @@ export const makeThreadMoveContextReader = Effect.gen(function* () { AND t.thread_id <> ${threadId} AND ( (t.parent_thread_id = ${threadId} AND t.attached_to_parent = 1) + OR t.thread_id = ${thread.parentThreadId} OR COALESCE(t.worktree_path, p.workspace_root) = ${checkout} ) `; diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index 34b5b9497..e0094253b 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -29,6 +29,7 @@ import { childReportMessageId, clampLaunchToCeiling, } from "../childThreadDecisions.ts"; +import { familyWorkStopped } from "../threadMoveCarry.ts"; import { childDeliveryAfterRestart, childDeliveryForQuietCandidate, @@ -100,6 +101,12 @@ export const makeChildThreadReactor = Effect.gen(function* () { ), ); + /** + * Settles a parent's request, unless the parent's move stopped what acts + * for its family (familyWorkStopped): a frozen parent would refuse it, and + * an answer refused there is lost. Its move waited for, or ended, every + * request it had. + */ const settle = ( parent: OrchestrationThread, request: OrchestrationChildRequest, @@ -111,6 +118,7 @@ export const makeChildThreadReactor = Effect.gen(function* () { }, ) => Effect.gen(function* () { + if (familyWorkStopped(parent)) return; yield* dispatch( { type: "thread.child-request.settle", @@ -187,11 +195,13 @@ export const makeChildThreadReactor = Effect.gen(function* () { const parent = yield* readThread(parentId); const request = parent?.childRequests.open.find((entry) => entry.requestId === requestId); // A child on a linked computer is set up there (RemoteChildReactor). + // A parent whose move stopped its agent starts nothing. if ( parent === undefined || request === undefined || request.status !== "starting" || - request.remote !== undefined + request.remote !== undefined || + familyWorkStopped(parent) ) { return; } @@ -320,7 +330,7 @@ export const makeChildThreadReactor = Effect.gen(function* () { if (parent === undefined || child === undefined || request === undefined) { return; } - if (!isQuietCandidate(child, request)) { + if (!isQuietCandidate(child, request) || familyWorkStopped(parent)) { return; } const delivery = childDeliveryForQuietCandidate(child, request); @@ -404,7 +414,8 @@ export const makeChildThreadReactor = Effect.gen(function* () { for (const summary of shell?.threads ?? []) { if (summary.awaitedChildThreadCount === 0 && !summary.pendingChildApproval) continue; const parent = yield* readThread(summary.id); - if (parent === undefined) continue; + // A parent whose move stopped its agent is left as it is (familyWorkStopped). + if (parent === undefined || familyWorkStopped(parent)) continue; for (const request of parent.childRequests.open) { if (request.status === "awaiting_user") { if (mode === "off") { @@ -482,6 +493,7 @@ export const makeChildThreadReactor = Effect.gen(function* () { const report = queued.find((entry) => entry.fromThread?.kind === "report"); const status = summary.session?.status; return report === undefined || + familyWorkStopped(summary) || queued.some((entry) => !isAgentOrigin(entry)) || status === "running" || status === "starting" diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 4f948d6e6..0a4147041 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -161,7 +161,7 @@ import { isCancelledReport } from "../childThreadDecisions.ts"; import { NO_BACKGROUND_TASKS } from "../sessionBackgroundTasks.ts"; import { isRestorePaid } from "../threadMoveDecisions.ts"; import { isLinkFenced } from "../linkFence.ts"; -import { isRoomAgentQueued } from "../threadMoveCarry.ts"; +import { drainsWhileMoveWaits } from "../threadMoveCarry.ts"; import { SideAnswerStartError } from "../Errors.ts"; const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError); const isProviderAdapterValidationError = Schema.is(ProviderAdapterValidationError); @@ -497,15 +497,16 @@ const owesMovedConversation = ( /** * What a thread's queue still sends while its move waits (docs/design/ - * fleet.md, Part 3f, review change 4): a room agent's hand-off or reply, so - * the room's chain drains and the thread gets free; the user's own messages - * wait to go with it. Nothing from `quiescing` on, nor once it moves. + * fleet.md, Part 3f, review change 4): a room agent's hand-off or reply, and + * its family's requests and answers (drainsWhileMoveWaits), so what it has + * going drains and the thread gets free; the user's own messages wait to go + * with it. Nothing from `quiescing` on, nor once it moves. */ -const roomDrainHead = ( - thread: Pick, +const moveDrainHead = ( + thread: Pick, ): OrchestrationQueuedFollowUp | undefined => (thread.move ?? null) === null && thread.pendingMove?.stage === "waiting" - ? (thread.queuedFollowUps ?? []).find(isRoomAgentQueued) + ? (thread.queuedFollowUps ?? []).find((entry) => drainsWhileMoveWaits(thread, entry)) : undefined; const decodeFellBackPayload = Schema.decodeUnknownOption(ThreadNativeSessionFellBackPayload); @@ -5856,7 +5857,7 @@ const make = Effect.gen(function* () { // While a move waits or runs the queue waits too, or the thread never // gets free; a room agent's hand-off or reply drains while it waits. const waitsForMove = queueWaitsForMove(thread); - if (waitsForMove && roomDrainHead(thread)?.messageId !== event.payload.followUp.messageId) { + if (waitsForMove && moveDrainHead(thread)?.messageId !== event.payload.followUp.messageId) { return; } if (status === "running" || status === "starting") { @@ -6060,9 +6061,9 @@ const make = Effect.gen(function* () { } const thread = yield* resolveThread(threadId); // A turn that ended while a move waits is what the move waited for; only - // a room agent's hand-off or reply still goes (roomDrainHead). + // a room agent's hand-off or reply, or the family's traffic, still goes (moveDrainHead). const waitsForMove = thread !== undefined && queueWaitsForMove(thread); - if (waitsForMove && roomDrainHead(thread) === undefined) { + if (waitsForMove && moveDrainHead(thread) === undefined) { return; } if (turnFinished && thread !== undefined && !waitsForMove) { @@ -6070,7 +6071,7 @@ const make = Effect.gen(function* () { } const next = thread ? waitsForMove - ? roomDrainHead(thread) + ? moveDrainHead(thread) : nextQueuedFollowUp(thread) : undefined; if (!thread || !next) { diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 68f5effc3..ca909b6ce 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -1377,6 +1377,56 @@ export function decideParentAttachmentSet( ]; } +/** Activity on a child whose parent moved to another computer without it. */ +export const ParentMovedAwayActivityKind = "thread.parent-moved-away"; + +/** + * A child that stays on this computer when its parent moves to another one + * (docs/design/fleet.md, Part 3f, (g)): it becomes its own thread, as a + * separation makes it, and its timeline says why ("Its parent thread moved + * to Windows PC, so this is its own thread now."). The parent can't reach it + * from there. + */ +export function leftBehindEvents( + readModel: OrchestrationReadModel, + baseFor: ChildEventBase, + parent: OrchestrationThread, + child: OrchestrationThread, + targetLabel: string, + at: string, +): ReadonlyArray { + const words = `Its parent thread moved to ${targetLabel}, so this is its own thread now.`; + return [ + { + ...baseFor(child.id), + type: "thread.parent-attachment-set", + payload: { + threadId: child.id, + attached: false, + attachmentEpoch: child.parentAttachmentEpoch + 1, + at, + }, + }, + ...separationEvents(readModel, baseFor, parent, child, at), + { + ...baseFor(child.id), + type: "thread.activity-appended", + payload: { + threadId: child.id, + activity: { + id: EventId.make(`parent-moved-away:${child.id}:${child.parentAttachmentEpoch + 1}`), + tone: "info", + kind: ParentMovedAwayActivityKind, + summary: words, + payload: { parentThreadId: parent.id, targetLabel }, + turnId: null, + createdAt: at, + }, + }, + }, + ]; +} + /** What the parent loses when `child` leaves its family. */ function separationEvents( readModel: OrchestrationReadModel, diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index a13ca3c09..72fed9775 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -1,4 +1,6 @@ import { + ChildRequestBatchId, + ChildRequestId, CommandId, CommandRunId, EnvironmentId, @@ -9,6 +11,7 @@ import { SideTurnId, ThreadId, ThreadMoveBatchId, + ThreadMoveFamilyId, ThreadMoveId, ThreadMoveRequestId, ThreadParticipantId, @@ -2242,3 +2245,533 @@ describe("a room moves with its agents (Part 3f, (i))", () => { }); }); }); + +describe("a family moves together (Part 3f, (g))", () => { + const CHILD = ThreadId.make("thread-child"); + const OTHER_CHILD = ThreadId.make("thread-other-child"); + const FAMILY = ThreadMoveFamilyId.make("family-1"); + const TAKES: ThreadMoveTakes = { threadState: true, families: true }; + const PARENT_REQUEST = ThreadMoveRequestId.make("request-parent"); + const CHILD_REQUEST = ThreadMoveRequestId.make("request-child"); + const OTHER_REQUEST = ThreadMoveRequestId.make("request-other-child"); + const CHILD_TRANSFER = ThreadMoveId.make("transfer-child"); + const ASK = ChildRequestId.make("child-request-1"); + + const withChild = async (model: OrchestrationReadModel, id: ThreadId = CHILD) => + ( + await apply(model, { + type: "thread.create", + commandId: nextCommandId(), + threadId: id, + projectId: PROJECT, + title: id === CHILD ? "Fix tests" : "Review", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${id}`, + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand) + ).model; + const queueFor = ( + threadId: ThreadId, + requestId: ThreadMoveRequestId, + family?: { readonly parentThreadId?: ThreadId }, + mode: ThreadPendingMoveMode = "when-done", + takes: ThreadMoveTakes = TAKES, + ): OrchestrationCommand => ({ + type: "thread.move.queue", + commandId: nextCommandId(), + threadId, + requestId, + target: MAC_MINI, + agent: modelSelection, + mode, + requestedBy: { kind: "user" }, + targetTakes: takes, + ...(family !== undefined ? { family: { id: FAMILY, ...family } } : {}), + createdAt: now, + }); + const quiesceFor = ( + threadId: ThreadId, + requestId: ThreadMoveRequestId, + ): OrchestrationCommand => ({ + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId, + requestId, + createdAt: now, + }); + const startFor = ( + threadId: ThreadId, + requestId: ThreadMoveRequestId, + transferId: ThreadMoveId, + ): OrchestrationCommand => ({ + type: "thread.move.start", + commandId: nextCommandId(), + threadId, + transferId, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: requestId, + targetTakes: TAKES, + createdAt: now, + }); + /** The parent asks its child something, and waits for the answer. */ + const asked = ( + model: OrchestrationReadModel, + status: "running" | "awaiting_user" = "running", + remote?: { readonly environmentId: EnvironmentId; readonly label: string }, + ) => + project(model, "thread.child-request-submitted", { + threadId: THREAD, + request: { + requestId: ASK, + batchId: ChildRequestBatchId.make("child-batch-1"), + kind: "send", + from: { participantId: null }, + callerTurnId: TurnId.make("turn-ask"), + deliveryEpoch: 0, + status, + childThreadId: CHILD, + childMessageId: MessageId.make("m-ask"), + ...(remote !== undefined + ? { remote: { ...remote, threadId: CHILD, status: "accepted" }, text: "Check this" } + : {}), + createdAt: now, + }, + createdAt: now, + }); + const refusalsOf = (model: OrchestrationReadModel, threadId = THREAD) => + threadMoveRefusals(model, threadOf(model, threadId), TAKES); + + it("a child moves only with its parent's move, and the parent only to a computer that takes families", async () => { + let model = await withChild(await seeded()); + // Not before its parent, and not on its own (that is a later step). + expect( + (await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: THREAD }))).refusal, + ).toContain("Its parent thread didn't move."); + expect((await apply(model, queueFor(CHILD, CHILD_REQUEST))).refusal).toContain( + "moves with the thread that started it", + ); + // A computer that doesn't take families: today's words. + expect( + (await apply(model, queueFor(THREAD, PARENT_REQUEST, {}, "when-done", { threadState: true }))) + .refusal, + ).toContain("started other threads"); + // A move that doesn't wait (an older app) never takes the children along. + expect( + (await apply(model, { ...startMove(), targetTakes: TAKES } as OrchestrationCommand)).refusal, + ).toContain("started other threads"); + + ({ model } = await apply(model, queueFor(THREAD, PARENT_REQUEST, {}))); + expect(threadOf(model).pendingMove?.family).toEqual({ id: FAMILY }); + // A family that names another parent is refused. + expect( + (await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: OTHER_CHILD }))).refusal, + ).toContain("didn't start this one"); + ({ model } = await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: THREAD }))); + expect(threadOf(model, CHILD).pendingMove?.family).toEqual({ + id: FAMILY, + parentThreadId: THREAD, + }); + + // The parent's move ends: the child's can't go on. + ({ model } = await apply(model, { + type: "thread.move.unqueue", + commandId: nextCommandId(), + threadId: THREAD, + requestId: PARENT_REQUEST, + createdAt: now, + })); + expect(refusalsOf(model, CHILD)).toContainEqual({ + kind: "blocked", + code: "child", + words: "Its parent thread didn't move.", + }); + }); + + it("waits for the threads it started to report back; Stop and move now ends the wait as Stop does", async () => { + const working = await asked(await withChild(await seeded())); + expect(refusalsOf(working)).toContainEqual({ + kind: "wait", + code: "background", + words: "when the threads it started report back", + }); + expect( + refusalsOf(await asked(await withChild(await seeded()), "awaiting_user")), + ).toContainEqual({ kind: "wait", code: "approval", words: "once you answer" }); + const waiting = await apply(working, queueFor(THREAD, PARENT_REQUEST, {})); + expect(waiting.refusal).toBeNull(); + expect(threadOf(waiting.model).childRequests.open).toHaveLength(1); + + const { model, refusal } = await apply( + working, + queueFor(THREAD, PARENT_REQUEST, {}, "stop-now"), + ); + expect(refusal).toBeNull(); + const parent = threadOf(model); + expect(parent.childRequests.open).toEqual([]); + expect(parent.childRequests.deliveryEpoch).toBe(1); + expect(parent.pendingMove?.interrupted?.childRequestsStopped).toBe(1); + + // One on another computer is cancelled there, and stopped, through Stop's own outbox. + const remote = await asked(await withChild(await seeded()), "running", { + environmentId: EnvironmentId.make("environment-windows"), + label: "Windows PC", + }); + const stopped = await apply(remote, queueFor(THREAD, PARENT_REQUEST, {}, "stop-now")); + expect(threadOf(stopped.model).childRequests.remoteCancels).toMatchObject([ + { requestId: ASK, cancelRequest: true, stopThread: true }, + ]); + // Frozen, the parent still records that the other computer took them. + let frozen = (await apply(stopped.model, quiesceFor(THREAD, PARENT_REQUEST))).model; + frozen = (await apply(frozen, startFor(THREAD, PARENT_REQUEST, TRANSFER))).model; + expect(threadOf(frozen).move).not.toBeNull(); + const delivered = await apply(frozen, { + type: "thread.remote-cancels.delivered", + commandId: nextCommandId(), + threadId: THREAD, + requestIds: [ASK], + createdAt: now, + }); + expect(delivered.refusal).toBeNull(); + expect(threadOf(delivered.model).childRequests.remoteCancels ?? []).toEqual([]); + }); + + it("a child's answer still reaches its parent while the move waits, not once the agent is being stopped", async () => { + let model = await withChild(await seeded()); + ({ model } = await apply(model, queueFor(THREAD, PARENT_REQUEST, {}))); + model = await project(model, "thread.follow-up-queued", { + threadId: THREAD, + followUp: { + messageId: MessageId.make("m-report"), + text: "Tests pass now.", + attachments: [], + fromThread: { + threadId: CHILD, + requestId: ASK, + kind: "report", + deliveryEpoch: 0, + attachmentEpoch: 0, + }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }, + }); + // Something to wait for, not something to clear. + expect(refusalsOf(model).some((entry) => entry.kind === "blocked")).toBe(false); + const report = threadOf(model).queuedFollowUps?.[0]; + const send: OrchestrationCommand = { + type: "thread.follow-up.send-queued", + commandId: nextCommandId(), + threadId: THREAD, + messageId: MessageId.make("m-report"), + createdAt: now, + }; + const reportTurn = { + type: "thread.turn.start", + commandId: nextCommandId(), + threadId: THREAD, + message: { messageId: MessageId.make("m-report"), role: "user", text: "x", attachments: [] }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + } as OrchestrationCommand; + expect(threadMoveGuardRefusal(model, send)).toBeNull(); + expect(threadMoveGuardRefusal(model, reportTurn, report)).toBeNull(); + // New work stays refused: a new thread, or a new message to one. + expect( + threadMoveGuardRefusal(model, { + type: "thread.child.send", + commandId: nextCommandId(), + threadId: THREAD, + } as unknown as OrchestrationCommand), + ).toContain("waiting to move to Mac mini"); + // From the stop on ("Stop and move now"), nothing more goes. + model = await project(model, "thread.move-quiescing", { + threadId: THREAD, + requestId: PARENT_REQUEST, + updatedAt: now, + }); + expect(threadMoveGuardRefusal(model, send)).toContain("waiting to move to Mac mini"); + }); + + it("the parent's arrival there makes the children that stayed their own threads, with a line", async () => { + let model = await withChild(await withChild(await seeded()), OTHER_CHILD); + ({ model } = await apply(model, queueFor(THREAD, PARENT_REQUEST, {}))); + ({ model } = await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: THREAD }))); + ({ model } = await apply( + model, + queueFor(OTHER_CHILD, OTHER_REQUEST, { parentThreadId: THREAD }), + )); + // The other child's move ends before the parent moved: it stays its child here. + ({ model } = await apply(model, { + type: "thread.move.unqueue", + commandId: nextCommandId(), + threadId: OTHER_CHILD, + requestId: OTHER_REQUEST, + createdAt: now, + })); + expect(threadOf(model, OTHER_CHILD).attachedToParent).toBe(true); + ({ model } = await apply(model, quiesceFor(THREAD, PARENT_REQUEST))); + ({ model } = await apply(model, startFor(THREAD, PARENT_REQUEST, TRANSFER))); + expect(threadOf(model).move?.family).toEqual({ id: FAMILY }); + ({ model } = await apply(model, { + type: "thread.move.complete", + commandId: nextCommandId(), + threadId: THREAD, + transferId: TRANSFER, + movedThreadId: ThreadId.make("thread-there"), + createdAt: now, + })); + const stayed = threadOf(model, OTHER_CHILD); + expect(stayed.attachedToParent).toBe(false); + expect(stayed.activities.at(-1)).toMatchObject({ + kind: "thread.parent-moved-away", + summary: "Its parent thread moved to Mac mini, so this is its own thread now.", + }); + // The child that comes along stays its child, moving. + expect(threadOf(model, CHILD).attachedToParent).toBe(true); + // Then its own move is dropped there: it stays here, as its own thread. + ({ model } = await apply(model, quiesceFor(CHILD, CHILD_REQUEST))); + ({ model } = await apply(model, startFor(CHILD, CHILD_REQUEST, CHILD_TRANSFER))); + ({ model } = await apply(model, { + type: "thread.move.abort", + commandId: nextCommandId(), + threadId: CHILD, + transferId: CHILD_TRANSFER, + reason: "Mac mini couldn't take it.", + createdAt: now, + })); + expect(threadOf(model, CHILD).move ?? null).toBeNull(); + expect(threadOf(model, CHILD).attachedToParent).toBe(false); + expect(threadOf(model, CHILD).activities.at(-1)?.kind).toBe("thread.parent-moved-away"); + }); + + it("a folder a frozen member works in no longer holds the others' moves", async () => { + let model = await withChild(await seeded()); + // The parent works in its child's folder, and the child is at work there. + model = await project(model, "thread.meta-updated", { + threadId: THREAD, + worktreePath: `/worktrees/${CHILD}`, + worktreeOrigin: { kind: "thread", threadId: CHILD }, + updatedAt: now, + }); + model = await project(model, "thread.session-set", { + threadId: CHILD, + session: { + threadId: CHILD, + status: "running", + providerName: "codex", + runtimeMode: "auto", + activeTurnId: TurnId.make("turn-child"), + lastError: null, + updatedAt: now, + }, + }); + expect(refusalsOf(model).map((entry) => entry.code)).toContain("shared_checkout"); + // Frozen for its own move, it can't change a file there. + model = await project(model, "thread.move-started", { + threadId: CHILD, + transferId: CHILD_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + startedAt: now, + family: { id: FAMILY, parentThreadId: THREAD }, + }); + expect(refusalsOf(model).map((entry) => entry.code)).not.toContain("shared_checkout"); + }); + + it("two members sharing a folder, each holding a message for the move, don't wait on each other", async () => { + let model = await seeded(); + // The child works in its parent's folder. + ({ model } = await apply(model, { + type: "thread.create", + commandId: nextCommandId(), + threadId: CHILD, + projectId: PROJECT, + title: "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/flaky", + worktreePath: "/worktrees/fix-flaky", + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand)); + ({ model } = await apply(model, queueFor(THREAD, PARENT_REQUEST, {}))); + ({ model } = await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: THREAD }))); + // Each holds the user's own message, which goes with it. + for (const threadId of [THREAD, CHILD]) { + model = await project(model, "thread.follow-up-queued", { + threadId, + followUp: { + messageId: MessageId.make(`m-held-${threadId}`), + text: "and then this", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }, + }); + } + for (const threadId of [THREAD, CHILD]) { + expect(refusalsOf(model, threadId)).toEqual([]); + } + }); + + describe("arriving", () => { + const PARENT_HERE = ThreadId.make("thread-parent-here"); + const CHILD_HERE = ThreadId.make("thread-child-here"); + const importFor = ( + threadId: ThreadId, + extra: Record = {}, + familyKey: string | null = "family-key-1", + ): OrchestrationCommand => + ({ + type: "thread.import", + commandId: nextCommandId(), + threadId, + projectId: PROJECT, + title: threadId === PARENT_HERE ? "Fix the flaky test" : "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/flaky", + worktreePath: `/worktrees/${threadId}`, + movedFrom: { + ...MAC_MINI, + threadId: THREAD, + movedAt: now, + ...(familyKey !== null ? { familyKey } : {}), + }, + messages: [], + activities: [], + createdAt: now, + ...extra, + }) as OrchestrationCommand; + const under = (parentThreadId: ThreadId) => ({ + lineage: { parentThreadId, parentTurnId: TurnId.make("turn-started-it") }, + }); + + it("a child lands under the parent that came in its family, fenced on its own", async () => { + let { model } = await apply(await seeded(), importFor(PARENT_HERE)); + ({ model } = await apply(model, importFor(CHILD_HERE, under(PARENT_HERE)))); + const child = threadOf(model, CHILD_HERE); + expect(child).toMatchObject({ + parentThreadId: PARENT_HERE, + parentTurnId: "turn-started-it", + attachedToParent: true, + parentAttachmentEpoch: 0, + }); + expect(child.movedFrom?.fenced).toBe(true); + // The user's message in the parent lifts the parent's fence, not the child's. + ({ model } = await apply(model, { + type: "thread.turn.start", + commandId: nextCommandId(), + threadId: PARENT_HERE, + message: { messageId: MessageId.make("m-here"), role: "user", text: "Go", attachments: [] }, + sentFrom: { kind: "computer", place: "here" }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + } as OrchestrationCommand)); + expect(threadOf(model, PARENT_HERE).movedFrom?.fenced).toBeUndefined(); + expect(threadOf(model, CHILD_HERE).movedFrom?.fenced).toBe(true); + }); + + it("never lands a child under a thread of this computer's own, or one from another family", async () => { + let { model } = await apply(await seeded(), importFor(PARENT_HERE)); + // A thread this computer started itself, with no family. + expect((await apply(model, importFor(CHILD_HERE, under(THREAD)))).refusal).toContain( + "didn't move with it", + ); + expect( + (await apply(model, importFor(CHILD_HERE, under(PARENT_HERE), "family-key-2"))).refusal, + ).toContain("didn't move with it"); + expect( + (await apply(model, importFor(CHILD_HERE, under(PARENT_HERE), null))).refusal, + ).toContain("only land under a parent that moved with it"); + expect( + (await apply(model, importFor(CHILD_HERE, under(ThreadId.make("thread-nowhere"))))).refusal, + ).toContain("isn't here"); + // Nor under a child. + const withChildHere = (await apply(model, importFor(CHILD_HERE, under(PARENT_HERE)))).model; + expect( + ( + await apply( + withChildHere, + importFor(ThreadId.make("thread-grandchild"), under(CHILD_HERE)), + ) + ).refusal, + ).toContain("itself another thread's"); + // Nor under a parent deleted since. + ({ model } = await apply(model, { + type: "thread.delete", + commandId: nextCommandId(), + threadId: PARENT_HERE, + } as OrchestrationCommand)); + expect((await apply(model, importFor(CHILD_HERE, under(PARENT_HERE)))).refusal).toContain( + "isn't here", + ); + // A guest marker names only a member of its own family. + expect( + ( + await apply( + await seeded(), + importFor(CHILD_HERE, { worktreeOrigin: { kind: "thread", threadId: THREAD } }), + ) + ).refusal, + ).toContain("isn't its family's"); + // Nor bring a message another thread here holds: it would be moved out of that thread. + const withMessage = ( + await apply(model, { + type: "thread.turn.start", + commandId: nextCommandId(), + threadId: THREAD, + message: { + messageId: MessageId.make("m-mine"), + role: "user", + text: "Hi", + attachments: [], + }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + } as OrchestrationCommand) + ).model; + expect( + ( + await apply( + withMessage, + importFor(CHILD_HERE, { + messages: [ + { + messageId: MessageId.make("m-mine"), + role: "user", + text: "Hi", + turnId: null, + createdAt: now, + }, + ], + }), + ) + ).refusal, + ).toContain("already another thread's"); + const guest = await apply( + await seeded(), + importFor(CHILD_HERE, { worktreeOrigin: { kind: "thread", threadId: PARENT_HERE } }), + ); + expect(guest.refusal).toBeNull(); + expect(threadOf(guest.model, CHILD_HERE).worktreeOrigin).toEqual({ + kind: "thread", + threadId: PARENT_HERE, + }); + }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 38d2732cb..ebe941540 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -2767,6 +2767,57 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // A move that waits for the thread to be free (docs/design/fleet.md, Part 3b). case "thread.move.queue": { + // A parent with the children that move with it (Part 3f, (g)): all + // queued in this one decision, the parent first, so no member packs + // before the family's members are known. A child its own checks refuse + // is left out and stays here. + if (command.children !== undefined && command.children.length > 0) { + const family = command.family; + if (family === undefined || family.parentThreadId !== undefined) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "Only a family's parent queues its children.", + }); + } + const { children, ...parentCommand } = command; + const planned: PlannedOrchestrationEvent[] = []; + let nextReadModel = readModel; + let nextSequence = readModel.snapshotSequence; + const take = ( + decided: PlannedOrchestrationEvent | ReadonlyArray, + ) => + Effect.gen(function* () { + for (const event of Array.isArray(decided) ? decided : [decided]) { + planned.push(event); + nextSequence += 1; + nextReadModel = yield* projectEvent(nextReadModel, { + ...event, + sequence: nextSequence, + } as OrchestrationEvent).pipe(Effect.orDie); + } + }); + yield* take(yield* decideOrchestrationCommand({ command: parentCommand, readModel })); + for (const child of children) { + const decided = yield* decideOrchestrationCommand({ + command: { + type: "thread.move.queue", + commandId: command.commandId, + threadId: child.threadId, + requestId: child.requestId, + target: command.target, + mode: command.mode, + requestedBy: command.requestedBy, + ...(command.batchId !== undefined ? { batchId: command.batchId } : {}), + ...(command.targetTakes !== undefined ? { targetTakes: command.targetTakes } : {}), + family: { id: family.id, parentThreadId: command.threadId }, + createdAt: command.createdAt, + }, + readModel: nextReadModel, + }).pipe(Effect.result); + if (decided._tag === "Success") yield* take(decided.success); + } + return planned; + } const thread = yield* requireThread({ readModel, command, @@ -2775,10 +2826,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" const baseFor = childEventBase(command, command.createdAt); const decided = decideMoveQueue(readModel, thread, command, baseFor); // "Stop and move now" holds command output the way Stop does, so a - // command finishing later can't wake the agent the move stopped. + // command finishing later can't wake the agent the move stopped, and + // ends its waits on the threads it started as Stop does (Part 3f, (g)). const held = command.mode === "stop-now" && !("refusal" in decided) && decided.length > 0 - ? holdCommandOutputOnStop(thread, () => baseFor(thread.id), command.createdAt) + ? [ + ...holdCommandOutputOnStop(thread, () => baseFor(thread.id), command.createdAt), + ...childStopEvents(readModel, thread, command, command.createdAt), + ] : []; return yield* planChildThreadDecision( command.type, @@ -2795,10 +2850,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); const baseFor = childEventBase(command, command.createdAt); const decided = decideMoveSetMode(readModel, thread, command, baseFor); - // Holds command output the way Stop does, as a move queued this way does. + // Holds command output and ends child waits the way Stop does, as a + // move queued this way does. const held = !("refusal" in decided) && decided.length > 0 - ? holdCommandOutputOnStop(thread, () => baseFor(thread.id), command.createdAt) + ? [ + ...holdCommandOutputOnStop(thread, () => baseFor(thread.id), command.createdAt), + ...childStopEvents(readModel, thread, command, command.createdAt), + ] : []; return yield* planChildThreadDecision( command.type, @@ -2819,12 +2878,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return yield* planChildThreadDecision( command.type, command.type === "thread.move.unqueue" - ? decideMoveUnqueue(thread, command, baseFor) + ? decideMoveUnqueue(readModel, thread, command, baseFor) : command.type === "thread.move.quiesce" ? decideMoveQuiesce(readModel, thread, command, baseFor) : command.type === "thread.move.queue-status" ? decideMoveQueueStatus(thread, command, baseFor) - : decideMoveQueueEnd(thread, command, baseFor), + : decideMoveQueueEnd(readModel, thread, command, baseFor), ); } @@ -2878,9 +2937,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" : command.type === "thread.move.cancel" ? decideMoveCancel(thread, command, baseFor) : command.type === "thread.move.abort" - ? decideMoveAbort(thread, command, baseFor) + ? decideMoveAbort(readModel, thread, command, baseFor) : command.type === "thread.move.complete" - ? decideMoveComplete(thread, command, baseFor) + ? decideMoveComplete(readModel, thread, command, baseFor) : command.type === "thread.native-session.fall-back" ? decideNativeSessionFallBack(thread, command, baseFor) : decideHistorySeedDelivered(thread, command, baseFor), diff --git a/apps/server/src/orchestration/threadMoveCarry.ts b/apps/server/src/orchestration/threadMoveCarry.ts index 2b387d347..3b61dae3d 100644 --- a/apps/server/src/orchestration/threadMoveCarry.ts +++ b/apps/server/src/orchestration/threadMoveCarry.ts @@ -28,12 +28,18 @@ import { linkedPullRequestArmed } from "@threadlines/shared/linkedPullRequests"; import { pullRequestSwitchesWords } from "@threadlines/shared/threadMoveProjection"; import { isRoomThread } from "@threadlines/shared/threadParticipants"; -/** What a move view needs of a project to tell a General Chats thread. */ +/** + * What a move view needs of a project to tell a General Chats thread, and + * (when it has them) of other threads to tell a parent. + */ export interface ThreadMoveCarryView { readonly projects: ReadonlyArray<{ readonly id: OrchestrationThread["projectId"]; readonly kind?: string | undefined; }>; + readonly threads?: ReadonlyArray< + Pick + >; } export interface ThreadMoveCarry { @@ -65,12 +71,18 @@ export interface ThreadMoveCarry { readonly room: boolean; /** Its agents outside work still limits (OrchestrationOutsideWork). */ readonly outsideWork: ReadonlyArray; + /** + * (g) It started threads (here, or on other computers, or waits on some), + * or another thread started it: it moves as part of a family. + */ + readonly family: boolean; /** What the other computer must take for this thread to move there. */ readonly needs: { readonly threadState: boolean; readonly generalChats: boolean; readonly rooms: boolean; readonly outsideWork: boolean; + readonly families: boolean; }; } @@ -80,8 +92,48 @@ export const ALL_MOVE_TAKES: ThreadMoveTakes = { generalChats: true, rooms: true, outsideWork: true, + families: true, +}; + +/** + * A message from the thread's own family (docs/design/fleet.md, Part 3f, + * (g)): a child's answer queued in its parent, here or from another + * computer, or its parent's request queued in a child. A lead chat's pass + * isn't one: the lead never moves. + */ +export const isFamilyQueued = ( + thread: Pick, + entry: OrchestrationQueuedFollowUp, +) => { + const origin = entry.fromThread; + return ( + origin !== undefined && + origin.ceiling === undefined && + (origin.kind === "report" || + (origin.environmentId === undefined && origin.threadId === thread.parentThreadId)) + ); }; +/** + * Whether what acts for a thread's family stops for it (docs/design/fleet.md, + * Part 3f, rule 5 and review change 4): from the move's stop on (`quiescing`) + * and while it is frozen or moved away. A move still waiting (`waiting`) + * lets the answers it waits for keep settling. + */ +export const familyWorkStopped = (thread: Pick) => + (thread.move ?? null) !== null || thread.pendingMove?.stage === "quiescing"; + +/** + * What a thread's queue still sends while its move waits (docs/design/ + * fleet.md, Part 3f, review change 4): a room agent's hand-off or reply, and + * its family's requests and answers, so what the thread already has going + * finishes and it gets free. The user's own messages wait to go with it. + */ +export const drainsWhileMoveWaits = ( + thread: Pick, + entry: OrchestrationQueuedFollowUp, +) => isRoomAgentQueued(entry) || isFamilyQueued(thread, entry); + /** A message a room agent queued for another (a hand-off or a reply): the room's chain drains it. */ export const isRoomAgentQueued = (entry: OrchestrationQueuedFollowUp) => entry.fromAgent !== undefined && @@ -117,10 +169,15 @@ export function waitingPlanOf( ); } -/** What a move's stop took, merged with what the thread holds now (it is only ever added to). */ +/** + * What a move's stop took, merged with what the thread holds now (it is only + * ever added to). `childRequestsStopped`: the waits on its children this stop + * ends (Part 3f, (g)), added to the ones earlier stops ended. + */ export function mergeInterrupted( thread: Pick, earlier: ThreadMoveInterrupted | null | undefined, + childRequestsStopped = 0, ): ThreadMoveInterrupted | undefined { const goalActive = earlier?.goalActive === true || thread.goal?.status === "active"; const byId = new Map(); @@ -129,10 +186,12 @@ export function mergeInterrupted( const checkBacks = [...byId.values()].toSorted((left, right) => left.scheduledFor.localeCompare(right.scheduledFor), ); - if (!goalActive && checkBacks.length === 0) return undefined; + const stopped = (earlier?.childRequestsStopped ?? 0) + childRequestsStopped; + if (!goalActive && checkBacks.length === 0 && stopped === 0) return undefined; return { ...(goalActive ? { goalActive: true as const } : {}), ...(checkBacks.length > 0 ? { checkBacks } : {}), + ...(stopped > 0 ? { childRequestsStopped: stopped } : {}), }; } @@ -143,7 +202,11 @@ export function sameInterrupted( ): boolean { const ids = (value: ThreadMoveInterrupted | null | undefined) => (value?.checkBacks ?? []).map((checkBack) => checkBack.id).join("\0"); - return (left?.goalActive === true) === (right?.goalActive === true) && ids(left) === ids(right); + return ( + (left?.goalActive === true) === (right?.goalActive === true) && + ids(left) === ids(right) && + (left?.childRequestsStopped ?? 0) === (right?.childRequestsStopped ?? 0) + ); } /** What the thread's move under way or waiting recorded its stop took. */ @@ -179,6 +242,16 @@ export function threadMoveCarry( const planWaiting = waitingPlanOf(thread) !== null; const room = isRoomThread(thread) || thread.agentRequests.open.length > 0; const outsideWork = thread.outsideWork ?? []; + const family = + (thread.parentThreadId !== null && thread.attachedToParent) || + (thread.childRequests.remoteChildren ?? []).length > 0 || + thread.childRequests.open.length > 0 || + (view.threads ?? []).some( + (candidate) => + candidate.parentThreadId === thread.id && + candidate.attachedToParent && + candidate.deletedAt === null, + ); return { goal, goalWorking: interrupted?.goalActive === true, @@ -192,7 +265,9 @@ export function threadMoveCarry( planWaiting, room, outsideWork, + family, needs: { + families: family, threadState: (goal !== null && goal.status !== "complete") || checkBacks.length > 0 || @@ -217,6 +292,7 @@ export function carryNotTaken( ): string | null { if (carry.needs.generalChats && takes?.generalChats !== true) return "it's a general chat"; if (carry.needs.rooms && takes?.rooms !== true) return "it has more than one agent"; + if (carry.needs.families && takes?.families !== true) return "it started other threads"; if (carry.needs.outsideWork && takes?.outsideWork !== true) { return "an outside assistant's work limits its agent here"; } diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 0643ab315..2f7b59e68 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -23,6 +23,7 @@ import { type OrchestrationThread, type OrchestrationThreadMove, type ThreadId, + type ThreadMoveFamily, type ThreadMoveHold, type ThreadMoveInterrupted, type ThreadMoveRestore, @@ -49,9 +50,11 @@ import { isValidParticipantId } from "@threadlines/shared/threadParticipants"; import { arrivalMessageText, resumedGoalMessageText } from "../moves/arrivalMessage.ts"; import { decideAgentChainStop } from "./agentRequestDecisions.ts"; import { derivedUuid } from "./childRequestIds.ts"; -import { childHasLiveWork } from "./childThreadDecisions.ts"; +import { childHasLiveWork, leftBehindEvents } from "./childThreadDecisions.ts"; import { + drainsWhileMoveWaits, interruptedOf, + isFamilyQueued, isRoomAgentQueued, mergeInterrupted, sameInterrupted, @@ -129,6 +132,14 @@ const wait = (code: ThreadMoveWaitCode, words = WAIT_WORDS[code]): ThreadMoveRef /** A room's agents still asking each other: no wait code of its own (a closed set), its own words. */ const ROOM_CHAIN_WORDS = "when its agents finish"; +/** A parent waiting on its children's answers (Part 3f, (g)): the `background` code, its own words. */ +const FAMILY_WAIT_WORDS = "when the threads it started report back"; +/** A child whose parent's move ended before it, or was never there. */ +export const PARENT_DIDNT_MOVE_WORDS = "Its parent thread didn't move."; +const CHILD_WORDS = + "This thread belongs to the thread that started it. Make it its own thread first."; +const FAMILY_CHILD_WORDS = + "This thread moves with the thread that started it. Move that thread to bring this one along, or make this its own thread first."; const blocked = (code: ThreadMoveBlockCode, words: string): ThreadMoveRefusalEntry => ({ kind: "blocked", code, @@ -151,7 +162,10 @@ export interface ThreadMoveView { * files: its worktree, else its project's folder. A general chat works in a * folder of its own (generalChatThreadScratchCwd), so no two of them share one. */ -function checkoutOf(readModel: ThreadMoveView, thread: OrchestrationThread) { +export function checkoutOf( + readModel: Pick, + thread: Pick, +) { if (thread.worktreePath !== null) return thread.worktreePath; const project = readModel.projects.find((entry) => entry.id === thread.projectId); if (project === undefined) return null; @@ -180,17 +194,21 @@ function foreignQueuedWords(entry: OrchestrationQueuedFollowUp): string { * The same check runs in `moves.preview` (so the dialog explains before * anyone clicks), in `thread.move.queue`, and in the freeze decision. A * pending move isn't one of them: each caller decides about that itself. + * `family` is the family the move goes with (Part 3f, (g)): the thread's own + * queued move's or move's when not given. */ export function threadMoveRefusals( readModel: ThreadMoveView, thread: OrchestrationThread, takes?: ThreadMoveTakes | null, + family: ThreadMoveFamily | undefined = thread.pendingMove?.family ?? thread.move?.family, ): ReadonlyArray { const found: ThreadMoveRefusalEntry[] = []; // What rides along (docs/design/fleet.md, Part 3e) is refused only when the // other computer doesn't take it. Absent `takes`: nothing beyond v1. const carry = threadMoveCarry(readModel, thread); const takesState = takes?.threadState === true; + const takesFamilies = takes?.families === true; if (thread.deletedAt !== null) found.push(blocked("deleted", "This thread was deleted.")); if (thread.archivedAt !== null) { found.push(blocked("archived", "Archived threads can't move. Unarchive it first.")); @@ -239,13 +257,26 @@ export function threadMoveRefusals( blocked("remote_origin", "This thread was started from another computer, so it stays here."), ); } + // A child moves only with its parent (Part 3f, (g)): its move names the + // parent's family, and the parent holds a move of that family (waiting, + // under way, or done). Moving alone across the link is a later step. if (thread.parentThreadId !== null && thread.attachedToParent) { - found.push( - blocked( - "child", - "This thread belongs to the thread that started it. Make it its own thread first.", - ), - ); + const withParent = + takesFamilies && + family?.parentThreadId === thread.parentThreadId && + parentHoldsFamily(readModel, family); + if (!withParent) { + found.push( + blocked( + "child", + takesFamilies && family?.parentThreadId !== undefined + ? PARENT_DIDNT_MOVE_WORDS + : takesFamilies + ? FAMILY_CHILD_WORDS + : CHILD_WORDS, + ), + ); + } } const hasLocalChildren = readModel.threads.some( (candidate) => @@ -254,18 +285,24 @@ export function threadMoveRefusals( candidate.deletedAt === null, ); if ( - hasLocalChildren || - (thread.childRequests.remoteChildren ?? []).length > 0 || - thread.childRequests.open.length > 0 + !takesFamilies && + (hasLocalChildren || + (thread.childRequests.remoteChildren ?? []).length > 0 || + thread.childRequests.open.length > 0) ) { found.push(blocked("has_children", "Threads that started other threads can't move yet.")); } // A message queued by something on this computer answers to it (a // scheduled run, an outside assistant, another thread), so it is sent // here. The user's own travel when the other computer takes them. - // A room agent's hand-off or reply drains while the move waits (Part 3f, - // review change 4): something to wait for, not something to clear. - const foreign = carry.foreignQueued.find((entry) => !(takesRooms && isRoomAgentQueued(entry))); + // A room agent's hand-off or reply, and the family's own requests and + // answers, drain while the move waits (Part 3f, review change 4): + // something to wait for, not something to clear. + const foreign = carry.foreignQueued.find( + (entry) => + !(takesRooms && isRoomAgentQueued(entry)) && + !(takesFamilies && isFamilyQueued(thread, entry)), + ); if (foreign !== undefined) { found.push(blocked("queued_messages", foreignQueuedWords(foreign))); } else if (carry.queuedFollowUps.length > 0 && !takesState) { @@ -345,6 +382,20 @@ export function threadMoveRefusals( found.push(wait("side_turn", ROOM_CHAIN_WORDS)); } } + // Waiting on the threads it started (Part 3f, (g)): "Move when it's done" + // waits for their answers; a start waiting for the user's OK, for them. + if (takesFamilies) { + const open = thread.childRequests.open; + if (open.some((request) => request.status === "awaiting_user")) { + found.push(wait("approval")); + } + if ( + open.some((request) => request.status !== "awaiting_user") || + (thread.queuedFollowUps ?? []).some((entry) => isFamilyQueued(thread, entry)) + ) { + found.push(wait("background", FAMILY_WAIT_WORDS)); + } + } if ( (session?.pendingBackgroundTaskCount ?? 0) > 0 || (session?.awaitedBackgroundTaskCount ?? 0) > 0 @@ -363,19 +414,59 @@ export function threadMoveRefusals( } if (thread.voiceActive === true) found.push(wait("voice")); // Another thread at work in the same checkout could change the files while - // they are being packed. + // they are being packed. One frozen for its own move can't: its agent is + // stopped, and nothing it holds (a plan, a queue) runs while it moves. + // A member of the same family's move waiting with it holds its user's + // queued messages and its plan for the move (they go along, not run here): + // only work that runs counts, or two members sharing a folder, each with a + // message queued, would wait on each other for good (Part 3f, (g)). const checkout = checkoutOf(readModel, thread); + const busyThere = (candidate: OrchestrationThread) => + family !== undefined && candidate.pendingMove?.family?.id === family.id + ? childHasLiveWork({ + ...candidate, + queuedFollowUps: (candidate.queuedFollowUps ?? []).filter((entry) => + drainsWhileMoveWaits(candidate, entry), + ), + proposedPlans: [], + }) + : childHasLiveWork(candidate); const sharedCheckoutBusy = readModel.threads.some( (candidate) => candidate.id !== thread.id && candidate.deletedAt === null && + (candidate.move ?? null) === null && checkoutOf(readModel, candidate) === checkout && - childHasLiveWork(candidate), + busyThere(candidate), ); if (sharedCheckoutBusy) found.push(wait("shared_checkout")); return found; } +/** + * Whether the parent a family names holds a move of that family: queued, + * under way, or done (Part 3f, (g)). A child's move is only ever queued, and + * only goes on, while it does. + */ +export function parentHoldsFamily( + readModel: Pick, + family: ThreadMoveFamily, +): boolean { + return holdsFamily( + readModel.threads.find((entry) => entry.id === family.parentThreadId), + family, + ); +} + +/** Whether `thread` (a family's parent, as read) holds a move of `family`. */ +export const holdsFamily = ( + thread: Pick | undefined, + family: ThreadMoveFamily, +) => + thread !== undefined && + thread.deletedAt === null && + (thread.pendingMove?.family?.id === family.id || thread.move?.family?.id === family.id); + /** The waits among a thread's move refusals, as clients see them. */ export function moveWaitsOf( refusals: ReadonlyArray, @@ -398,8 +489,9 @@ export function threadMoveRefusal( readModel: ThreadMoveView, thread: OrchestrationThread, takes?: ThreadMoveTakes | null, + family?: ThreadMoveFamily, ): string | null { - const refusals = threadMoveRefusals(readModel, thread, takes); + const refusals = threadMoveRefusals(readModel, thread, takes, family); const block = firstMoveBlock(refusals); if (block !== null) return block.words; const first = refusals[0]; @@ -436,6 +528,9 @@ const FROZEN_THREAD_COMMANDS: ReadonlySet = new Se "thread.realtime.state.set", "thread.settings-change.settle", "thread.settings-change.report-device", + // A linked computer confirmed the cancels the move's stop owed it (Part + // 3f, (g)): they drain from a frozen parent, never stranded on it. + "thread.remote-cancels.delivered", "thread.move.progress", "thread.move.cancel", "thread.move.abort", @@ -482,13 +577,18 @@ const WORK_START_COMMANDS: ReadonlySet = new Set([ // An agent's new request of another (a hand-off, an ask, a review, an // invite) starts work; its open ones still settle (Part 3f, review change 4). "thread.agent-request.submit", + // So does a new thread, or a new message to one; answers already owed + // still come back (Part 3f, (g), review change 4). + "thread.child.start", + "thread.child.send", ]); /** * Whether `command`, on its own thread, starts work there. While a move - * waits for its thread (`waiting`), a room agent's hand-off or reply already - * queued is still sent: the room's chain drains, so the thread gets free - * (docs/design/fleet.md, Part 3f, review change 4). Not from `quiescing` on. + * waits for its thread (`waiting`), a room agent's hand-off or reply, or the + * family's request or answer, already queued is still sent: what the thread + * has going drains, so it gets free (docs/design/fleet.md, Part 3f, review + * change 4). Not from `quiescing` on. */ function startsWork(command: OrchestrationCommand, thread: OrchestrationThread): boolean { if (!WORK_START_COMMANDS.has(command.type)) return false; @@ -510,7 +610,7 @@ function startsWork(command: OrchestrationCommand, thread: OrchestrationThread): return !( thread.pendingMove?.stage === "waiting" && queued !== undefined && - isRoomAgentQueued(queued) + drainsWhileMoveWaits(thread, queued) ); } default: @@ -519,9 +619,10 @@ function startsWork(command: OrchestrationCommand, thread: OrchestrationThread): } /** - * Whether `command` is the turn a room's queued hand-off or reply starts as - * it is sent while the move waits (docs/design/fleet.md, Part 3f, review - * change 4): the turn for exactly that message, only at `waiting`. + * Whether `command` is the turn a room's queued hand-off or reply, or the + * family's request or answer, starts as it is sent while the move waits + * (docs/design/fleet.md, Part 3f, review change 4): the turn for exactly that + * message, only at `waiting`. */ function drainsRoomChain( thread: OrchestrationThread, @@ -534,7 +635,7 @@ function drainsRoomChain( command.message.messageId === drained.messageId && thread.pendingMove?.stage === "waiting" && (thread.move ?? null) === null && - isRoomAgentQueued(drained) + drainsWhileMoveWaits(thread, drained) ); } @@ -621,7 +722,11 @@ export function decideMoveStart( if (pending !== null) { return refuse(`A move to ${pending.target.label} is already waiting. Cancel it first.`); } - const refusal = threadMoveRefusal(readModel, thread, takes); + // A move that doesn't wait never takes a family (Part 3f, (g)): an app + // that starts one expects the thread's children to come, so a thread with + // any is refused as before. Families move through the queue. + const { families: _families, ...alone } = takes ?? {}; + const refusal = threadMoveRefusal(readModel, thread, alone); if (refusal !== null) return refuse(refusal); } else { if (pending === null || pending.requestId !== queuedRequestId) { @@ -661,6 +766,9 @@ export function decideMoveStart( ...(interrupted !== undefined ? { interrupted } : {}), ...(takes !== undefined ? { targetTakes: takes } : {}), ...(command.roomAgents !== undefined ? { roomAgents: command.roomAgents } : {}), + ...(pending?.family !== undefined && queuedRequestId !== undefined + ? { family: pending.family } + : {}), }, }; const queueEnded: PlannedEvent[] = @@ -812,7 +920,14 @@ export function decideMoveQueue( ? [] : refuse(`A move to ${pending.target.label} is already waiting. Cancel it first.`); } - const refusals = threadMoveRefusals(readModel, thread, command.targetTakes); + // A family's member names its family; a child's must be its parent's (Part 3f, (g)). + if ( + command.family?.parentThreadId !== undefined && + command.family.parentThreadId !== thread.parentThreadId + ) { + return refuse("That thread didn't start this one."); + } + const refusals = threadMoveRefusals(readModel, thread, command.targetTakes, command.family); const block = firstMoveBlock(refusals); if (block !== null) return refuse(block.words); // A command runs in the user's own terminal tab, which the server doesn't @@ -821,10 +936,13 @@ export function decideMoveQueue( return refuse(STOP_NOW_COMMAND_RUN_WORDS); } // What an earlier move that didn't happen still owes comes along, and what - // "Stop and move now" stops is recorded before it is gone. + // "Stop and move now" stops is recorded before it is gone: its waits on the + // threads it started end as Stop ends them (the caller plans that). const owed = thread.moveRestoreOwed ?? null; const interrupted = - command.mode === "stop-now" ? mergeInterrupted(thread, owed?.interrupted) : owed?.interrupted; + command.mode === "stop-now" + ? mergeInterrupted(thread, owed?.interrupted, thread.childRequests.open.length) + : owed?.interrupted; const queued: PlannedEvent = { ...baseFor(thread.id), type: "thread.move-queued", @@ -844,6 +962,7 @@ export function decideMoveQueue( ...(interrupted !== undefined ? { interrupted } : {}), ...(command.targetTakes !== undefined ? { targetTakes: command.targetTakes } : {}), ...(command.roomAgents !== undefined ? { roomAgents: command.roomAgents } : {}), + ...(command.family !== undefined ? { family: command.family } : {}), }, }, }; @@ -872,7 +991,11 @@ export function decideMoveSetMode( if (refusals.some((entry) => entry.code === "command_run")) { return refuse(STOP_NOW_COMMAND_RUN_WORDS); } - const interrupted = mergeInterrupted(thread, pending.interrupted); + const interrupted = mergeInterrupted( + thread, + pending.interrupted, + thread.childRequests.open.length, + ); const modeSet: PlannedEvent = { ...baseFor(thread.id), type: "thread.move-mode-set", @@ -884,13 +1007,34 @@ export function decideMoveSetMode( updatedAt: command.createdAt, }, }; - return sessionStopped(thread) && liveSideTurns(thread).length === 0 + return sessionStopped(thread) && + liveSideTurns(thread).length === 0 && + thread.childRequests.open.length === 0 ? [modeSet] : [modeSet, ...sessionStopEvents(thread, command.createdAt, baseFor)]; } +/** + * A child whose own move ended here after its parent moved to another + * computer (docs/design/fleet.md, Part 3f, (g)): it stays as its own thread, + * and says why. Nothing for any other thread. + */ +function leftBehindAfterParent( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + at: string, + baseFor: EventBase, +): ReadonlyArray { + if (thread.parentThreadId === null || !thread.attachedToParent) return []; + const parent = readModel.threads.find((entry) => entry.id === thread.parentThreadId); + const move = parent?.move ?? null; + if (parent === undefined || move === null || move.movedAway === undefined) return []; + return leftBehindEvents(readModel, baseFor, parent, thread, move.target.label, at); +} + /** Cancel: the queued move `requestId` ends; a cancel for an older one changes nothing. */ export function decideMoveUnqueue( + readModel: OrchestrationReadModel, thread: OrchestrationThread, command: CommandOf<"thread.move.unqueue">, baseFor: EventBase, @@ -898,6 +1042,7 @@ export function decideMoveUnqueue( const pending = currentPendingMove(thread, command.requestId); if (pending === null) return []; return [ + ...leftBehindAfterParent(readModel, thread, command.createdAt, baseFor), { ...baseFor(thread.id), type: "thread.move-queue-ended", @@ -1002,12 +1147,17 @@ export function decideMoveQueueStatus( * says why ("Didn't move: …") until the user dismisses it. */ export function decideMoveQueueEnd( + readModel: OrchestrationReadModel, thread: OrchestrationThread, command: CommandOf<"thread.move.queue-end">, baseFor: EventBase, ): ThreadMoveDecision { const pending = currentPendingMove(thread, command.requestId); if (pending === null) return []; + const leftBehind = + command.reason === "blocked" + ? leftBehindAfterParent(readModel, thread, command.createdAt, baseFor) + : []; const payload: ThreadMoveNotStartedPayload = { requestId: command.requestId, targetLabel: pending.target.label, @@ -1046,6 +1196,7 @@ export function decideMoveQueueEnd( ...(command.reason === "blocked" ? restoreOwedEvents(thread, pending.target, pending.interrupted, command.createdAt, baseFor) : []), + ...leftBehind, ]; } @@ -1105,8 +1256,12 @@ export function decideMoveCancel( ]; } -/** The other computer confirmed the move was dropped: the thread unfreezes, and says why. */ +/** + * The other computer confirmed the move was dropped: the thread unfreezes, and + * says why. A child whose parent moved meanwhile stays as its own thread. + */ export function decideMoveAbort( + readModel: OrchestrationReadModel, thread: OrchestrationThread, command: CommandOf<"thread.move.abort">, baseFor: EventBase, @@ -1145,10 +1300,18 @@ export function decideMoveAbort( }, }, ...restoreOwedEvents(thread, move.target, move.interrupted, command.createdAt, baseFor), + ...leftBehindAfterParent(readModel, thread, command.createdAt, baseFor), ]; } +/** + * The other computer committed the move: the thread lives there now, and its + * copy here is read-only. Its children here that didn't come with it (not + * moving in its family, archived ones aside) become their own threads in the + * same decision (docs/design/fleet.md, Part 3f, (g)). + */ export function decideMoveComplete( + readModel: OrchestrationReadModel, thread: OrchestrationThread, command: CommandOf<"thread.move.complete">, baseFor: EventBase, @@ -1156,6 +1319,22 @@ export function decideMoveComplete( const move = currentMove(thread, command.transferId); if (move === null) return refuse("This thread isn't moving."); if (move.movedAway !== undefined) return []; + const familyId = move.family?.id; + const comesAlong = (child: OrchestrationThread) => + familyId !== undefined && + (child.pendingMove?.family?.id === familyId || child.move?.family?.id === familyId); + const leftBehind = readModel.threads + .filter( + (child) => + child.parentThreadId === thread.id && + child.attachedToParent && + child.deletedAt === null && + child.archivedAt === null && + !comesAlong(child), + ) + .flatMap((child) => + leftBehindEvents(readModel, baseFor, thread, child, move.target.label, command.createdAt), + ); return [ { ...baseFor(thread.id), @@ -1168,6 +1347,7 @@ export function decideMoveComplete( }, }, ...readOnlyCopyEvents(thread, command.createdAt, baseFor), + ...leftBehind, ]; } @@ -1238,6 +1418,26 @@ export function decideThreadImport( } const roomRefusal = importedRoomRefusal(command); if (roomRefusal !== null) return refuse(roomRefusal); + const familyRefusal = importedFamilyRefusal(readModel, command); + if (familyRefusal !== null) return refuse(familyRefusal); + // Every id it brings is its own: one another thread here already has would + // move that thread's message into this one (the projection keys messages + // by id alone). + const incoming = new Set([ + ...command.messages.map((message) => message.messageId), + ...(command.queuedFollowUps ?? []).map((entry) => entry.messageId), + ...(command.arrival?.message !== undefined ? [command.arrival.message.messageId] : []), + ]); + if ( + readModel.threads.some( + (thread) => + thread.id !== command.threadId && + thread.messages.some((message) => incoming.has(message.id)), + ) + ) { + return refuse("A message it brings is already another thread's here."); + } + const lineage = command.lineage; const base = () => baseFor(command.threadId); const created: PlannedEvent = { ...base(), @@ -1251,6 +1451,17 @@ export function decideThreadImport( interactionMode: command.interactionMode, branch: command.branch, worktreePath: command.worktreePath, + // A child that came with its parent (Part 3f, (g)): in its family here, + // its answers owed nothing yet (a fresh attachment epoch). + ...(lineage !== undefined + ? { + parentThreadId: lineage.parentThreadId, + ...(lineage.parentTurnId !== null ? { parentTurnId: lineage.parentTurnId } : {}), + attachedToParent: true, + } + : {}), + // A family member in another member's folder: never its owner here. + ...(command.worktreeOrigin !== undefined ? { worktreeOrigin: command.worktreeOrigin } : {}), // It came from another computer: fenced until the user here sends it a message. movedFrom: { ...command.movedFrom, fenced: true }, historySeedOwed: true, @@ -1312,6 +1523,8 @@ export function decideThreadImport( ...(message.requestKind !== undefined ? { requestKind: message.requestKind } : {}), ...(message.requestOutcome !== undefined ? { requestOutcome: message.requestOutcome } : {}), ...(message.requestError !== undefined ? { requestError: message.requestError } : {}), + // A family's request or answer between threads that moved together. + ...(message.fromThread !== undefined ? { fromThread: message.fromThread } : {}), createdAt: message.createdAt, updatedAt: message.createdAt, }, @@ -1387,6 +1600,52 @@ function importedRoomRefusal(command: CommandOf<"thread.import">): string | null return null; } +/** + * Why a moved family member can't be written as it is, or null (docs/design/ + * fleet.md, Part 3f, (g)). A child lands under its parent only when that + * parent is here, came in the same family (the key this computer derived from + * the link both came over), is in the same project, isn't a child itself, and + * isn't moving on again: a linked computer can never put a thread under one + * of this computer's own. A guest marker names a member of the same family. + */ +function importedFamilyRefusal( + readModel: OrchestrationReadModel, + command: CommandOf<"thread.import">, +): string | null { + const familyKey = command.movedFrom.familyKey; + const lineage = command.lineage; + if (lineage !== undefined) { + const parent = readModel.threads.find((entry) => entry.id === lineage.parentThreadId); + if (familyKey === undefined) return "A thread can only land under a parent that moved with it."; + if (parent === undefined || parent.deletedAt !== null) { + return "The thread that started it isn't here."; + } + if ((parent.movedFrom ?? null)?.familyKey !== familyKey) { + return "The thread that started it didn't move with it."; + } + if (parent.projectId !== command.projectId) { + return "The thread that started it is in another project."; + } + if (parent.parentThreadId !== null && parent.attachedToParent) { + return "The thread that started it is itself another thread's."; + } + if ((parent.move ?? null) !== null || (parent.pendingMove ?? null) !== null) { + return "The thread that started it is moving again."; + } + } + const origin = command.worktreeOrigin; + if (origin !== undefined) { + if (familyKey === undefined || origin.kind !== "thread") { + return "Only a thread that moved with its family can work in another's folder."; + } + const owner = readModel.threads.find((entry) => entry.id === origin.threadId); + if (owner !== undefined && (owner.movedFrom ?? null)?.familyKey !== familyKey) { + return "The folder it works in isn't its family's."; + } + } + return null; +} + /** * What a moved thread had going, written with it (docs/design/fleet.md, Part * 3e): its goal as it arrives, its pull requests, its plans, and its queue diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 71f250b87..2cde8cfdb 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -138,6 +138,7 @@ import Migration0115 from "./Migrations/115_ThreadNativeSession.ts"; import Migration0116 from "./Migrations/116_ProjectLeadThread.ts"; import Migration0117 from "./Migrations/117_ThreadMoveCarry.ts"; import Migration0118 from "./Migrations/118_SessionStopRequestedTurn.ts"; +import Migration0119 from "./Migrations/119_LinkMoveFamilies.ts"; /** * Migration loader with all migrations defined inline. @@ -268,6 +269,7 @@ export const migrationEntries = [ [116, "ProjectLeadThread", Migration0116], [117, "ThreadMoveCarry", Migration0117], [118, "SessionStopRequestedTurn", Migration0118], + [119, "LinkMoveFamilies", Migration0119], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/119_LinkMoveFamilies.ts b/apps/server/src/persistence/Migrations/119_LinkMoveFamilies.ts new file mode 100644 index 000000000..0ca40cbd3 --- /dev/null +++ b/apps/server/src/persistence/Migrations/119_LinkMoveFamilies.ts @@ -0,0 +1,29 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Families that move together (docs/design/fleet.md, Part 3f, (g)): on the + * receiving computer, `link_moves.family_id` is the family's key here (from + * the link and the family's id) and `source_thread_id` the thread's id on the + * computer it left, so a child's import can find its parent's and wait for it + * to commit, and a member in another's folder can find that folder's owner. + * Null for every move made before, and for a thread that moves on its own. + * + * New nullable columns and an index; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const columns = yield* sql<{ readonly name: string }>` + SELECT name FROM pragma_table_info('link_moves') + `; + if (!columns.some((entry) => entry.name === "family_id")) { + yield* sql`ALTER TABLE link_moves ADD COLUMN family_id TEXT`; + } + if (!columns.some((entry) => entry.name === "source_thread_id")) { + yield* sql`ALTER TABLE link_moves ADD COLUMN source_thread_id TEXT`; + } + yield* sql` + CREATE INDEX IF NOT EXISTS idx_link_moves_family + ON link_moves(family_id, source_thread_id) + `; +}); diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 5c85e8043..97edd1e19 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -9,7 +9,7 @@ import { type OrchestrationThreadMove, ProjectId, ProviderInstanceId, - type ThreadId, + ThreadId, ThreadMoveBatchId, ThreadMoveError, ThreadMoveId, @@ -1058,6 +1058,101 @@ describe("ChatView (full app): moving a thread to another computer", () => { } }); + it("brings the threads it started that are ticked, and says which stay and why", async () => { + setPrimaryLinksSnapshot( + fleetLinksSnapshot({ + outbound: [fleetOutboundLink(FLEET_OFFLINE_ENVIRONMENT_ID, "Mac mini")], + }), + ); + const macMini = FLEET_MOVE_PREVIEW.targets[1]!; + const fixTests = ThreadId.make("thread-fix-tests"); + const review = ThreadId.make("thread-review"); + const planning = ThreadId.make("thread-planning"); + const queues: Array = []; + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-move-family" as MessageId, + targetText: "move family", + }), + configureFixture: withThreadMoveQueueFixture, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.movesPreview) { + return { + ...FLEET_MOVE_PREVIEW, + family: { + children: [ + { threadId: fixTests, title: "Fix tests" }, + { threadId: review, title: "Review" }, + { + threadId: planning, + title: "Planning", + refusal: "A command in this thread is waiting for you to run or dismiss it.", + }, + ], + remoteChildren: [ + { label: "Windows PC", title: "Changelog" }, + { label: "Windows PC", title: "Release notes" }, + ], + }, + targets: [macMini], + } satisfies ThreadMovePreview; + } + if (body._tag === WS_METHODS.movesQueue) { + queues.push(body); + return { requestId: QUEUED_REQUEST_ID }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await saveMacMini("connected"); + await openCommandPaletteFromTrigger(); + await page + .getByTestId("command-palette") + .getByText("Move to another computer", { exact: true }) + .click(); + const dialog = page.getByTestId("thread-move-dialog"); + await expect + .element(dialog.getByTestId("thread-move-family-coming")) + .toHaveTextContent("Its 2 threads move with it."); + // One that can't come says why, and that it stays. + await expect + .element(dialog.getByTestId(`thread-move-family-stays-${planning}`)) + .toHaveTextContent( + "A command in this thread is waiting for you to run or dismiss it. It stays here as its own thread.", + ); + await expect + .element(dialog.getByTestId("thread-move-family-remote")) + .toHaveTextContent( + "2 threads it started on Windows PC stay there. It can't reach them from Mac mini.", + ); + // Unticked, one stays here as its own thread. + await dialog.getByTestId(`thread-move-family-tick-${review}`).click(); + await expect + .element(dialog.getByTestId(`thread-move-family-stays-${review}`)) + .toHaveTextContent("Stays here as its own thread."); + await expect + .element(dialog.getByTestId("thread-move-family-coming")) + .toHaveTextContent("Its thread moves with it."); + + await dialog.getByTestId("thread-move-confirm").click(); + await expect.element(page.getByTestId("thread-move-dialog")).not.toBeInTheDocument(); + expect(queues).toEqual([ + expect.objectContaining({ + threadId: THREAD_ID, + targetEnvironmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + familySelection: "explicit", + children: [fixTests], + }), + ]); + } finally { + await mounted.cleanup(); + } + }); + it("says when a waiting move goes, holds new messages, and cancels the move it shows", async () => { setPrimaryLinksSnapshot( fleetLinksSnapshot({ @@ -1870,6 +1965,108 @@ describe("ChatView (full app): moving a thread to another computer", () => { threadIds: [THREAD_ID, chatId, goalId], targetEnvironmentId: FLEET_OFFLINE_ENVIRONMENT_ID, mode: "when-done", + familySelection: "explicit", + }), + ]); + } finally { + await mounted.cleanup(); + } + }); + + it("moves a family as one group: its threads under it, ticked with it, each one able to stay", async () => { + setPrimaryLinksSnapshot( + fleetLinksSnapshot({ + outbound: [fleetOutboundLink(FLEET_OFFLINE_ENVIRONMENT_ID, "Mac mini")], + }), + ); + const fixTestsId = "thread-family-fix-tests" as ThreadId; + const reviewId = "thread-family-review" as ThreadId; + const queueManys: Array = []; + const base = createSnapshotForTargetUser({ + targetMessageId: "msg-user-move-family-batch" as MessageId, + targetText: "move family batch", + }); + const snapshot = [fixTestsId, reviewId].reduce(addThreadToSnapshot, base); + const titles = new Map([ + [fixTestsId, "Fix tests"], + [reviewId, "Review"], + ]); + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: { + ...snapshot, + threads: snapshot.threads.map((thread) => + titles.has(thread.id) + ? { + ...thread, + title: titles.get(thread.id)!, + parentThreadId: THREAD_ID, + attachedToParent: true, + } + : thread, + ), + }, + configureFixture: (fixture) => + withMoveCapabilities(fixture, { + threadMove: true, + threadMoveQueue: true, + threadMoveBatch: true, + threadMoveState: true, + }), + resolveRpc: (body) => { + if (body._tag === WS_METHODS.movesPreviewMany) { + const threadIds = (body as unknown as { threadIds: ThreadId[] }).threadIds; + return { + threads: threadIds.map((threadId) => + threadId === THREAD_ID + ? { threadId, waitsFor: [{ code: "turn" as const, words: "when this turn ends" }] } + : { threadId }, + ), + targets: [{ ...FLEET_MOVE_PREVIEW.targets[1]!, projectName: undefined }], + }; + } + if (body._tag === WS_METHODS.movesQueueMany) { + queueManys.push(body); + return { batchId: "batch-family", queued: [], refused: [] }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await saveMacMini("connected"); + await openCommandPaletteFromTrigger(); + await page + .getByTestId("command-palette") + .getByText("Move threads to another computer…", { exact: true }) + .click(); + const dialog = page.getByTestId("move-threads-dialog"); + await expect.element(dialog.getByTestId("move-threads-list")).toBeVisible(); + // The parent leads (its agent works), its threads right under it, all ticked with it. + const rows = Array.from( + document.querySelectorAll('[data-testid^="move-threads-row-"]'), + ).map((row) => row.dataset.testid); + expect(rows).toEqual([ + `move-threads-row-${THREAD_ID}`, + `move-threads-row-${fixTestsId}`, + `move-threads-row-${reviewId}`, + ]); + for (const id of [THREAD_ID, fixTestsId, reviewId]) { + await expect.element(dialog.getByTestId(`move-threads-tick-${id}`)).toBeChecked(); + } + // One unticked stays here; the rest go, exactly those. + await dialog.getByTestId(`move-threads-tick-${reviewId}`).click(); + await expect.element(dialog.getByTestId(`move-threads-tick-${THREAD_ID}`)).toBeChecked(); + await expect + .element(dialog.getByTestId("move-threads-confirm")) + .toHaveTextContent("Move 2 threads"); + await dialog.getByTestId("move-threads-confirm").click(); + await expect.element(page.getByTestId("move-threads-dialog")).not.toBeInTheDocument(); + expect(queueManys).toEqual([ + expect.objectContaining({ + threadIds: [THREAD_ID, fixTestsId], + familySelection: "explicit", }), ]); } finally { diff --git a/apps/web/src/components/MoveThreadsDialogContent.tsx b/apps/web/src/components/MoveThreadsDialogContent.tsx index fcdaef811..6a74f89be 100644 --- a/apps/web/src/components/MoveThreadsDialogContent.tsx +++ b/apps/web/src/components/MoveThreadsDialogContent.tsx @@ -26,12 +26,14 @@ import { cn } from "../lib/utils"; import { isSidebarThreadRunning } from "../store"; import { describeMoveCandidate, + groupMoveFamilies, isThreadMoveTargetPickable, listMoveCandidates, type MoveCandidate, orderMoveCandidates, pickDefaultMoveTarget, threadMoveStopNowRefusal, + toggleMoveFamily, } from "../threadMove"; import type { MoveThreadsDialogRequest } from "./MoveThreadsDialog"; import { closeMoveThreadsDialog } from "./MoveThreadsDialog"; @@ -96,17 +98,22 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial isThreadMoveTargetPickable(candidate), ) ?? pickDefaultMoveTarget(preview.targets); setTargetId(target?.environmentId ?? null); - // Working ones that can go come ticked; idle ones wait for the user. + // Working ones that can go come ticked, each with its family (Part + // 3f, (g)); idle ones wait for the user. + const canGo = (threadId: ThreadId) => { + const thread = preview.threads.find((entry) => entry.threadId === threadId); + return ( + thread !== undefined && + describeMoveCandidate(thread, target?.environmentId ?? null).kind !== "refused" + ); + }; setTicked( - new Set( - preview.threads - .filter( - (thread) => - (thread.waitsFor ?? []).length > 0 && - describeMoveCandidate(thread, target?.environmentId ?? null).kind !== "refused", - ) - .map((thread) => thread.threadId), - ), + preview.threads + .filter((thread) => (thread.waitsFor ?? []).length > 0 && canGo(thread.threadId)) + .reduce>( + (ticks, thread) => toggleMoveFamily(ticks, candidates, thread.threadId, true, canGo), + new Set(), + ), ); setPreviewState({ status: "ready", preview }); } catch (error) { @@ -131,20 +138,24 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial ), [preview], ); + // Each family together, a parent's children under it (Part 3f, (g)). const rows = useMemo( () => - orderMoveCandidates(candidates, previewById).flatMap((candidate) => { - const threadPreview = previewById.get(candidate.threadId); - return threadPreview - ? [ - { - candidate, - preview: threadPreview, - words: describeMoveCandidate(threadPreview, targetId, target?.label), - }, - ] - : []; - }), + groupMoveFamilies(orderMoveCandidates(candidates, previewById)).flatMap( + ({ candidate, depth }) => { + const threadPreview = previewById.get(candidate.threadId); + return threadPreview + ? [ + { + candidate, + depth, + preview: threadPreview, + words: describeMoveCandidate(threadPreview, targetId, target?.label), + }, + ] + : []; + }, + ), [candidates, previewById, targetId, target?.label], ); // What goes: the ticked rows that can go to the computer picked now. @@ -159,13 +170,12 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial const canMove = target !== null && isThreadMoveTargetPickable(target) && chosen.length > 0 && !queueing; + // A family moves as one group: ticking any member ticks all of it that can + // go, and its members can be unticked one by one (they stay here). const toggle = (threadId: ThreadId, on: boolean) => { - setTicked((current) => { - const next = new Set(current); - if (on) next.add(threadId); - else next.delete(threadId); - return next; - }); + const canGo = (id: ThreadId) => + rows.some((row) => row.candidate.threadId === id && row.words.kind !== "refused"); + setTicked((current) => toggleMoveFamily(current, candidates, threadId, on, canGo)); }; const move = async () => { @@ -177,6 +187,8 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial threadIds: chosen.map((row) => row.candidate.threadId), targetEnvironmentId: target.environmentId, mode, + // Exactly the threads ticked: a parent's unticked children stay here. + familySelection: "explicit", }); // Its target's Fleet row and page say how it goes, refusals included. rememberMoveBatch({ @@ -340,6 +352,8 @@ function CandidateList({ }: { readonly rows: ReadonlyArray<{ readonly candidate: MoveCandidate; + /** 1: a child, under its parent. */ + readonly depth: 0 | 1; readonly words: ReturnType; }>; readonly ticked: ReadonlySet; @@ -352,13 +366,14 @@ function CandidateList({ aria-label="Threads" data-testid="move-threads-list" > - {rows.map(({ candidate, words }) => { + {rows.map(({ candidate, depth, words }) => { const refused = words.kind === "refused"; return (