From 5e6f8135dba8235aa865c7a4cd92b7a9a3429a86 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:00:27 -0500 Subject: [PATCH] feat: a thread moves across the link its work came over Step 4b, last part (docs/design/fleet.md, Part 3f). A child thread can move alone to another computer and stay its parent's child there, with the receiving computer writing its link origin from its own authenticated link; a thread another computer's agent started can move back home and nowhere else; and a thread still fenced from a move can only go back where it came from until a person here takes it over. A parent and a lone child never move against each other, and a shared folder waits for everything still running in it. Rebuilt on main after #984. --- apps/server/src/guide/topics.ts | 2 +- apps/server/src/links/LinkMoves.test.ts | 235 +++++- apps/server/src/links/LinkMoves.ts | 142 +++- apps/server/src/links/LinkRequests.ts | 20 + apps/server/src/links/RemoteChildReactor.ts | 11 +- apps/server/src/links/peerRoute.ts | 1 + apps/server/src/moves/MoveQueue.ts | 4 +- apps/server/src/moves/ThreadMoves.test.ts | 107 +++ apps/server/src/moves/ThreadMoves.ts | 98 ++- apps/server/src/moves/familyMove.ts | 37 + apps/server/src/moves/moveExport.ts | 7 + .../Layers/ProjectionPipeline.ts | 6 +- .../src/orchestration/childThreadDecisions.ts | 158 +++- .../orchestration/decider.threadMoves.test.ts | 692 +++++++++++++++++- apps/server/src/orchestration/linkFence.ts | 7 +- apps/server/src/orchestration/projector.ts | 2 +- .../src/orchestration/threadMoveCarry.ts | 10 + .../src/orchestration/threadMoveDecisions.ts | 369 ++++++++-- .../ChatView.move-thread.browser.tsx | 95 +++ .../components/ThreadMoveDialogContent.tsx | 121 ++- apps/web/src/store.ts | 2 +- apps/web/src/threadMove.ts | 10 + docs/design/fleet.md | 15 + packages/contracts/src/moves.ts | 19 +- packages/contracts/src/orchestration.test.ts | 127 +++- packages/contracts/src/orchestration.ts | 34 + packages/contracts/src/peerRpc.ts | 47 ++ packages/shared/src/childThreads.ts | 12 +- 28 files changed, 2292 insertions(+), 98 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index eb9e03ffc..14e533adc 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 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.`, +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, and the thread can move only back to the computer it came from. 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 can move on its own (Move just this thread) or with its whole family. On its own it stays that thread's thread on the other computer, which can still send to it, read it and stop it; there, like any thread another computer's agent started, its agent never gets other threads, rooms or schedules. A thread another computer's agent started can move only back to that computer, where it is that thread's thread again. 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/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index 6c718a4e7..953ae2475 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -174,6 +174,12 @@ interface CarryRecord { readonly generalChatsRoot?: string; /** The moved thread as it reads here once it landed (its queue, its session). */ readonly shell?: () => OrchestrationThreadShell | undefined; + /** The computer the link was made for, when its invite pinned it. */ + readonly pinnedEnvironmentId?: string; + /** The link's name for that computer here (its device row). */ + readonly linkLabel?: string; + /** Threads already here, as their rows read. */ + readonly threadsHere?: ReadonlyArray<{ readonly threadId: ThreadId } & Record>; } /** The services LinkMoves leans on, with this computer's git real and the rest faked. */ @@ -202,7 +208,7 @@ function testLayer( ok: true, access, maxRuntimeMode: "auto-accept-edits", - pinnedEnvironmentId: null, + pinnedEnvironmentId: carry.pinnedEnvironmentId ?? null, }, ), projectForKey: () => @@ -258,14 +264,18 @@ function testLayer( } as never), getThreadShellById: () => Effect.succeed(Option.fromUndefinedOr(carry.shell?.())), }), - // A thread here once its import was dispatched (a family's child reads its parent). + // A thread here once its import was dispatched (a family's child reads + // its parent), or one that was here already. Layer.mock(ProjectionThreadRepository)({ getById: ({ threadId }) => - Effect.succeed( - Option.fromUndefinedOr( - dispatched - .filter((command) => command.type === "thread.import") - .find((command) => command.threadId === threadId) === undefined + Effect.sync(() => { + const here = carry.threadsHere?.find((row) => row.threadId === threadId); + if (here !== undefined) return Option.some(here as never); + const imported = dispatched + .flatMap((command) => (command.type === "thread.import" ? [command] : [])) + .find((command) => command.threadId === threadId); + return Option.fromUndefinedOr( + imported === undefined ? undefined : ({ threadId, @@ -273,11 +283,19 @@ function testLayer( deletedAt: null, move: null, pendingMove: null, + remoteOrigin: imported.remoteOrigin ?? null, } as never), - ), + ); + }), + }), + Layer.mock(RelayDeviceRepository)({ + getDevice: () => + Effect.succeed( + carry.linkLabel === undefined + ? Option.none() + : Option.some({ label: carry.linkLabel } as never), ), }), - Layer.mock(RelayDeviceRepository)({ getDevice: () => Effect.succeed(Option.none()) }), // Every agent here is a Claude whose home is `carry.home`. Layer.mock(ProviderService)({ getInstanceInfo: () => @@ -333,7 +351,10 @@ const pack = ( repos: ReturnType, nativeSession?: NativeSessionExport | null, state?: PeerMoveThreadState, - room?: Pick & { + room?: Pick & { + /** What the move says the computer it leaves calls itself. */ + readonly sourceEnvironmentId?: EnvironmentId | undefined; + readonly sourceLabel?: string; readonly thread?: OrchestrationThread; /** Another thread of the same checkout (a family member), as its own transfer. */ readonly threadId?: ThreadId; @@ -351,6 +372,7 @@ const pack = ( transferId, dir, family: room?.family, + linkLineage: room?.linkLineage, attachmentsDir: path.join(repos.root, "attachments"), thread: room?.thread ?? movingThread(), room: room?.room, @@ -359,8 +381,8 @@ const pack = ( subdirectory: "", canonicalKey: "example.com/repo", source: { - environmentId: EnvironmentId.make("environment-windows"), - environmentLabel: "Windows PC", + environmentId: room?.sourceEnvironmentId ?? EnvironmentId.make("environment-windows"), + environmentLabel: room?.sourceLabel ?? "Windows PC", threadId: room?.threadId ?? ThreadId.make("thread-a"), }, agent, @@ -1933,3 +1955,192 @@ describe("a family moving here (Part 3f, (g))", () => { ); }); }); + +describe("a thread moving across its link (Part 3f, (h))", () => { + const WINDOWS = "environment-windows"; + const PARENT_THERE = ThreadId.make("thread-parent-on-windows"); + const PARENT_HERE = ThreadId.make("thread-parent-here"); + const remoteParent = { remoteParent: { threadId: PARENT_THERE, title: "Ship it" } }; + const home = { home: { parentThreadId: PARENT_HERE } }; + const importOf = (dispatched: ReadonlyArray) => { + const found = dispatched.find((command) => command.type === "thread.import"); + return found?.type === "thread.import" ? found : assert.fail("nothing was imported"); + }; + /** This computer's thread, holding `threadId` on `environmentId` as its child there. */ + const parentHere = (environmentId: string, threadId: string) => ({ + threadId: PARENT_HERE, + projectId: ProjectId.make("project-b"), + deletedAt: null, + move: null, + pendingMove: null, + parentThreadId: null, + attachedToParent: 0, + childRequests: { + open: [], + deliveryEpoch: 0, + startsSinceUser: 0, + sendsSinceUser: 0, + pendingNotes: [], + remoteChildren: [ + { + environmentId, + label: "Windows PC", + threadId, + handle: "Agent", + title: "Move me", + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: "2026-11-17T10:00:00.000Z", + }, + ], + }, + }); + const moved = ( + repos: ReturnType, + dispatched: OrchestrationCommand[], + lineage: NonNullable, + carry: Partial & { readonly sourceEnvironmentId?: EnvironmentId } = {}, + ) => + Effect.gen(function* () { + const packed = yield* pack(repos, null, undefined, { + linkLineage: lineage, + sourceEnvironmentId: carry.sourceEnvironmentId, + // What the move says it is called never names anything here. + sourceLabel: "Not Windows", + }); + return yield* deliver(packed.manifest, packed.payload); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + linkLabel: "Windows PC", + ...carry, + }), + ), + ); + + it.live("a child alone stays its parent's child, its link taken from the link itself", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const state = yield* moved(repos, dispatched, remoteParent, { + pinnedEnvironmentId: WINDOWS, + }); + assert.equal(state.status, "committed"); + assert.equal(state.keptParent, true); + const imported = importOf(dispatched); + assert.deepEqual(imported.remoteOrigin, { + linkDeviceId: "device-windows", + environmentId: EnvironmentId.make(WINDOWS), + environmentPinned: true, + environmentLabel: "Windows PC", + threadId: PARENT_THERE, + threadTitle: "Ship it", + }); + assert.equal(imported.movedFrom.environmentId, WINDOWS); + assert.isUndefined(imported.lineage); + assert.isUndefined(imported.adopt); + }); + }); + + it.live("a link that can't prove its computer, or a forged one, keeps no parent", () => { + const unpinned = makeRepos(); + const forged = makeRepos(); + const first: OrchestrationCommand[] = []; + const second: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const plain = yield* moved(unpinned, first, remoteParent); + assert.equal(plain.status, "committed"); + assert.isUndefined(plain.keptParent); + assert.isUndefined(importOf(first).remoteOrigin); + assert.include( + importOf(first).arrival?.left ?? [], + "This computer can't confirm its link to Windows PC, so this is its own thread and 'Ship it' there can't reach it.", + ); + // The move says it came from a computer the link wasn't made for. + const lied = yield* moved(forged, second, remoteParent, { + pinnedEnvironmentId: WINDOWS, + sourceEnvironmentId: EnvironmentId.make("environment-mac"), + }); + assert.equal(lied.status, "committed"); + assert.isUndefined(lied.keptParent); + assert.isUndefined(importOf(second).remoteOrigin); + }); + }); + + it.live("comes home under its parent only when this computer's own records hold it", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + yield* moved(repos, dispatched, home, { + pinnedEnvironmentId: WINDOWS, + threadsHere: [parentHere(WINDOWS, "thread-a")], + }); + const imported = importOf(dispatched); + assert.deepEqual(imported.adopt, { parentThreadId: PARENT_HERE }); + assert.isUndefined(imported.remoteOrigin); + }); + }); + + it.live("a home claim this computer's records don't back lands as its own thread", () => { + const cases = [ + // The parent here never held that thread. + { pinnedEnvironmentId: WINDOWS, threadsHere: [parentHere(WINDOWS, "thread-other")] }, + // It held a thread of that id on another computer, not the one this link is for. + { pinnedEnvironmentId: WINDOWS, threadsHere: [parentHere("environment-mac", "thread-a")] }, + // A link that can't prove its computer. + { threadsHere: [parentHere(WINDOWS, "thread-a")] }, + // No such parent here at all. + { pinnedEnvironmentId: WINDOWS }, + ]; + return Effect.forEach(cases, (carry) => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return moved(repos, dispatched, home, carry).pipe( + Effect.map((state) => { + assert.equal(state.status, "committed"); + const imported = importOf(dispatched); + assert.isUndefined(imported.adopt); + assert.isUndefined(imported.lineage); + assert.include( + imported.arrival?.left ?? [], + "The thread that started it isn't on this computer anymore, so this is its own thread.", + ); + }), + ); + }); + }); + + it("refuses a manifest naming both a parent and a home, itself, or a family too", () => { + const base = { + totalBytes: 0, + sha256: "x", + parts: [], + source: { environmentId: "e", environmentLabel: "Windows PC", threadId: "thread-a" }, + git: { headSha: "h", branch: null, baseSha: null }, + thread: { messages: [], activities: [] }, + } as unknown as PeerMoveManifest; + assert.include( + moveManifestRefusal({ ...base, linkLineage: { ...remoteParent, ...home } }), + "not both", + ); + assert.include(moveManifestRefusal({ ...base, linkLineage: {} }), "not both"); + assert.include( + moveManifestRefusal({ + ...base, + linkLineage: { remoteParent: { threadId: ThreadId.make("thread-a"), title: "Me" } }, + }), + "itself as its parent", + ); + assert.include( + moveManifestRefusal({ + ...base, + linkLineage: home, + family: { id: ThreadMoveFamilyId.make("family-1") }, + }), + "moves on no link", + ); + assert.isNull(moveManifestRefusal({ ...base, linkLineage: home })); + }); +}); diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index b7aabdcf6..8e22bf010 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -33,6 +33,7 @@ import { CommandId, type ComputerLinkPendingRequest, ComputerLinkError, + EnvironmentId, EventId, GENERAL_CHATS_PROJECT_ID, isScratchMoveManifest, @@ -70,6 +71,7 @@ import { PeerRpcError, ThreadId, type ThreadImportMessage, + type ThreadRemoteOrigin, type ThreadMoveRespondManyInput, type ThreadMoveRespondManyResult, TurnId, @@ -369,10 +371,31 @@ export function moveManifestRefusal(manifest: PeerMoveManifest): string | null { return ( moveRoomRefusal(manifest) ?? moveFamilyRefusal(manifest) ?? + moveLinkLineageRefusal(manifest) ?? moveStateRefusal(manifest.thread.state) ); } +/** + * Why a thread moving across the link its work came over can't be taken, or + * null (docs/design/fleet.md, Part 3f, (h)): it names one parent or one + * home, never both, never itself, and never with a family. What it names is + * only ever a claim: the import checks it against this computer's own link + * and records (linkLanding). + */ +function moveLinkLineageRefusal(manifest: PeerMoveManifest): string | null { + const lineage = manifest.linkLineage; + if (lineage === undefined) return null; + if ((lineage.remoteParent === undefined) === (lineage.home === undefined)) { + return "it names one parent or one home, not both"; + } + if (manifest.family !== undefined) return "a thread moving with its family moves on no link"; + if (lineage.remoteParent?.threadId === manifest.source.threadId) { + return "it names itself as its parent"; + } + return null; +} + /** * 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 @@ -2279,6 +2302,82 @@ const make = Effect.gen(function* () { }; }; + /** + * How a thread moving across the link its work came over lands here + * (docs/design/fleet.md, Part 3f, (h)), decided from this computer's own + * link and records alone; the manifest only says which thread it means. + * + * - A child that moved without its parent (`remoteParent`) stays that + * parent's child across the link: its `remoteOrigin` is this link, and + * the computer this link was made for. A link that can't prove which + * computer that is lands it as its own thread. + * - A thread coming home (`home`) lands under the parent here only when + * that parent holds exactly this thread, on exactly the computer this + * link was made for, as its child: a linked computer can never put a + * thread under one of this computer's own. + * + * Anything else lands as a thread of its own, with the "Moved here" words + * saying why (`left`). + */ + const linkLanding = ( + row: LinkMoveRow, + projectId: string, + pinnedEnvironmentId: string | null, + fromLabel: string, + ) => + Effect.gen(function* () { + const lineage = row.manifest.linkLineage; + if (lineage === undefined || row.familyKey !== null) return {}; + const source = row.manifest.source; + // The computer this link was made for, and the one the move says it came from. + const home = + pinnedEnvironmentId !== null && pinnedEnvironmentId === source.environmentId + ? EnvironmentId.make(pinnedEnvironmentId) + : null; + const remoteParent = lineage.remoteParent; + if (remoteParent !== undefined) { + if (home === null) { + return { + left: `This computer can't confirm its link to ${fromLabel}, so this is its own thread and '${remoteParent.title}' there can't reach it.`, + }; + } + const remoteOrigin: ThreadRemoteOrigin = { + linkDeviceId: row.linkDeviceId, + environmentId: home, + environmentPinned: true, + environmentLabel: fromLabel, + threadId: remoteParent.threadId, + threadTitle: remoteParent.title, + }; + return { remoteOrigin, environmentId: home }; + } + const parentThreadId = lineage.home?.parentThreadId; + if (parentThreadId === undefined) return {}; + const own = { + left: "The thread that started it isn't on this computer anymore, so this is its own thread.", + }; + if (home === null) return own; + const found = yield* threadRows + .getById({ threadId: parentThreadId }) + .pipe( + Effect.mapError( + () => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` }), + ), + ); + const parent = Option.getOrUndefined(found); + const holds = + parent !== undefined && + parent.deletedAt === null && + (parent.move ?? null) === null && + (parent.pendingMove ?? null) === null && + !((parent.parentThreadId ?? null) !== null && (parent.attachedToParent ?? 0) > 0) && + parent.projectId === projectId && + (parent.childRequests?.remoteChildren ?? []).some( + (entry) => entry.environmentId === home && entry.threadId === source.threadId, + ); + return holds ? { adopt: { parentThreadId }, environmentId: home } : own; + }); + /** * 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/ @@ -2472,6 +2571,14 @@ const make = Effect.gen(function* () { // 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); + // Across the link its work came over (Part 3f, (h)): from this link alone. + const across = yield* linkLanding( + row, + land.project.id, + authority.pinnedEnvironmentId, + fromLabel, + ); + if (across.left !== undefined) familyLeft.push(across.left); // The "Moved here" line's room words first, then its family's, then // what the thread had going. const arrival = @@ -2505,7 +2612,7 @@ const make = Effect.gen(function* () { branch: scratch ? null : row.branch, worktreePath: scratch ? null : row.worktreePath, movedFrom: { - environmentId: row.manifest.source.environmentId, + environmentId: across.environmentId ?? row.manifest.source.environmentId, label: fromLabel, threadId: row.manifest.source.threadId, movedAt: now, @@ -2519,6 +2626,8 @@ const make = Effect.gen(function* () { messages: [...roomMessages, ...notSent], activities, ...(lineage?.lineage !== undefined ? { lineage: lineage.lineage } : {}), + ...(across.remoteOrigin !== undefined ? { remoteOrigin: across.remoteOrigin } : {}), + ...(across.adopt !== undefined ? { adopt: across.adopt } : {}), ...(family?.worktreeOrigin !== undefined ? { worktreeOrigin: family.worktreeOrigin } : {}), @@ -3340,12 +3449,33 @@ const make = Effect.gen(function* () { Effect.asVoid, ); + /** + * A committed move's answer says whether the thread landed as its parent's + * child across this link (`keptParent`, docs/design/fleet.md, Part 3f, + * (h)): read from the thread itself, which only this computer wrote, so a + * retried call answers the same. + */ + const withKeptParent = (link: PeerLink) => (answer: Effect.Effect) => + Effect.flatMap(answer, (state) => + state.status !== "committed" || state.threadId === undefined + ? Effect.succeed(state) + : threadRows.getById({ threadId: state.threadId }).pipe( + Effect.map((row) => + Option.isSome(row) && row.value.remoteOrigin?.linkDeviceId === link.deviceId + ? { ...state, keptParent: true as const } + : state, + ), + // Never read as "its own thread" when it may not be: the asker tries again. + Effect.mapError(() => peerFailure(`${ownLabel()} couldn't read its threads.`)), + ), + ); + return LinkMoves.of({ - prepare, - chunk, - finish, - status, - abort, + prepare: (link, input) => prepare(link, input).pipe(withKeptParent(link)), + chunk: (link, input) => chunk(link, input).pipe(withKeptParent(link)), + finish: (link, input) => finish(link, input).pipe(withKeptParent(link)), + status: (link, input) => status(link, input).pipe(withKeptParent(link)), + abort: (link, input) => abort(link, input).pipe(withKeptParent(link)), respond, respondMany, pending, diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 123da92e7..492f0e754 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -1961,6 +1961,26 @@ const make = Effect.gen(function* () { yield* publishThreadStatus(event.payload.threadId); return; } + // A thread this link started moved on (back to the computer that + // started it, docs/design/fleet.md, Part 3f, (h)): what it was asked + // here ends, as an archive ends it. + case "thread.moved-away": { + const rows = yield* ledger + .listByThread(event.payload.threadId) + .pipe(Effect.orElseSucceed(() => [])); + if (rows.every(isTerminalLinkRequest)) return; + const thread = yield* readThread(event.payload.threadId); + const label = thread?.move?.target.label ?? "another computer"; + for (const row of rows) { + if (isTerminalLinkRequest(row)) continue; + yield* settle( + row, + "failed", + `'${thread?.title ?? "That thread"}' moved to ${label} before it finished.`, + ); + } + return; + } default: return; } diff --git a/apps/server/src/links/RemoteChildReactor.ts b/apps/server/src/links/RemoteChildReactor.ts index 529dd01bc..b59777120 100644 --- a/apps/server/src/links/RemoteChildReactor.ts +++ b/apps/server/src/links/RemoteChildReactor.ts @@ -1183,9 +1183,18 @@ const make = Effect.gen(function* () { const onEvent = (event: OrchestrationEvent) => Effect.gen(function* () { if (event.type === "thread.remote-child-updated") { - // Followed from its first record; a word the user gave here goes out. const child = event.payload.child; const environmentId = child.environmentId; + // Came home (docs/design/fleet.md, Part 3f, (h)): no longer followed + // there, so an open watch starts over without it. + if (event.payload.removed === true) { + holdersByChild + .get(childKey(environmentId, child.threadId)) + ?.delete(event.payload.threadId); + if (watching.has(environmentId)) rewatch.add(environmentId); + return; + } + // Followed from its first record; a word the user gave here goes out. follow(environmentId, event.payload.threadId, child.threadId); const owed = wrapOwed(child); if (owed) addTo(wrapOwers, environmentId, event.payload.threadId); diff --git a/apps/server/src/links/peerRoute.ts b/apps/server/src/links/peerRoute.ts index b8de82f9a..88b8f4244 100644 --- a/apps/server/src/links/peerRoute.ts +++ b/apps/server/src/links/peerRoute.ts @@ -225,6 +225,7 @@ export const makePeerRpcLayer = (input: { moveRooms: true, moveOutsideWork: true, moveFamilies: true, + moveLinkLineage: true, threadFiling: true, outsideAgents: true, } satisfies PeerDescriptor; diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts index 9b3dd5382..8bb04017e 100644 --- a/apps/server/src/moves/MoveQueue.ts +++ b/apps/server/src/moves/MoveQueue.ts @@ -1146,7 +1146,9 @@ export const makeMoveQueue = ( if (event.payload.reason !== "started") yield* lookAtAll(settleDelay, false); return; } - if (event.type === "thread.move-aborted") { + // A move that settled: a parent waiting for its child's own move + // to finish (Part 3f, (h)) looks again. + if (event.type === "thread.move-aborted" || event.type === "thread.moved-away") { yield* lookAtAll(settleDelay, false); } // A move that didn't happen owes the thread what it took. diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index 87f2f870f..f00e13746 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -32,6 +32,7 @@ import { sessionsThatFit, } from "./moveExport.ts"; import { carryBringsWords, threadMoveCarry } from "../orchestration/threadMoveCarry.ts"; +import { linkLineageOf } from "./familyMove.ts"; import { seenThroughOf } from "./roomMove.ts"; import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts"; @@ -402,6 +403,112 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { expect(current.refusal).toBeUndefined(); }); + it("a thread another computer's agent started goes only home, and says so per computer (Part 3f, (h))", () => { + const thread = threadWith({ + remoteOrigin: { + linkDeviceId: "device-mac", + environmentId: MAC_MINI, + environmentPinned: true, + environmentLabel: "Mac mini", + threadId: ThreadId.make("thread-on-mac"), + threadTitle: "Ship it", + }, + }); + const carry = threadMoveCarry(view, thread); + const third = targetPreviewOf( + { + environmentId: EnvironmentId.make("environment-linux"), + label: "Linux box", + described: Option.some(peer({ moveThreadState: true, moveLinkLineage: true })), + }, + { thread, place, carry }, + ); + expect(third.refusal).toBe( + "This thread was started by an agent on Mac mini, which still directs it. It can move back to Mac mini, not to another computer.", + ); + expect(third.refusalCode).toBeUndefined(); + expect( + targetPreviewOf(target(peer({ moveThreadState: true })), { thread, place, carry }).refusal, + ).toBe( + "Update Threadlines on Mac mini to move this thread: an agent on another computer started it.", + ); + expect( + targetPreviewOf(target(peer({ moveThreadState: true, moveLinkLineage: true })), { + thread, + place, + carry, + }).refusal, + ).toBeUndefined(); + // Its manifest names home only to home. + expect(linkLineageOf([thread], thread, MAC_MINI)).toEqual({ + home: { parentThreadId: "thread-on-mac" }, + }); + expect( + linkLineageOf([thread], thread, EnvironmentId.make("environment-linux")), + ).toBeUndefined(); + }); + + it("a moved thread still fenced is offered only the computer it came from (Part 3f, (h))", () => { + const thread = threadWith({ + movedFrom: { + environmentId: MAC_MINI, + label: "Mac mini", + threadId: ThreadId.make("thread-on-mac"), + movedAt: "2026-11-17T10:00:00.000Z", + fenced: true, + }, + }); + const carry = threadMoveCarry(view, thread); + const described = peer({ moveThreadState: true, moveLinkLineage: true }); + expect( + targetPreviewOf( + { + environmentId: EnvironmentId.make("environment-linux"), + label: "Linux box", + described: Option.some(described), + }, + { thread, place, carry }, + ).refusal, + ).toBe( + "This thread moved here from Mac mini, and until you send it a message here it can only move back to Mac mini.", + ); + expect(targetPreviewOf(target(described), { thread, place, carry }).refusal).toBeUndefined(); + }); + + it("a child moves alone only to a computer that keeps it its parent's (Part 3f, (h))", () => { + const parent = threadWith({ + id: ThreadId.make("thread-parent"), + title: "Ship it", + deletedAt: null, + }); + const child = threadWith({ parentThreadId: parent.id, attachedToParent: true }); + const carry = threadMoveCarry(view, child); + expect( + targetPreviewOf(target(peer({ moveThreadState: true, moveFamilies: true })), { + thread: child, + place, + carry, + }).aloneRefusal, + ).toBe("Update Threadlines on Mac mini to move it without the thread that started it."); + expect( + targetPreviewOf( + target(peer({ moveThreadState: true, moveFamilies: true, moveLinkLineage: true })), + { thread: child, place, carry }, + ).aloneRefusal, + ).toBeUndefined(); + expect(linkLineageOf([parent, child], child, MAC_MINI)).toEqual({ + remoteParent: { threadId: parent.id, title: "Ship it" }, + }); + // A parent whose own move is only queued waits for this one: still its parent there. + const queued = { ...parent, pendingMove: { requestId: "request-parent" } } as never; + expect(linkLineageOf([queued, child], child, MAC_MINI)).toEqual({ + remoteParent: { threadId: parent.id, title: "Ship it" }, + }); + // One frozen for its own move can't be reached from there: it arrives as its own thread. + const frozen = { ...parent, move: { transferId: "transfer-parent" } } as never; + expect(linkLineageOf([frozen, child], child, MAC_MINI)).toBeUndefined(); + }); + it("warns per agent picked, in the server's words", () => { const thread = threadWith({ goal: goal("active", 50_000), diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts index 07543f1ca..e6ea85ff0 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -77,13 +77,15 @@ import { import { firstMoveBlock, holdsFamily, + fencedMoveRefusal, moveWaitsOf, + remoteOriginElsewhereWords, threadMoveRefusal, threadMoveRefusals, type ThreadMoveView, } from "../orchestration/threadMoveDecisions.ts"; import { ThreadActionGate } from "./ThreadActionGate.ts"; -import { familyManifestOf, familyThreadIdsOf } from "./familyMove.ts"; +import { familyManifestOf, familyThreadIdsOf, linkLineageOf } from "./familyMove.ts"; import { cantComeWords, movingRoomAgents, @@ -287,6 +289,7 @@ export function takesOf(peer: PeerDescriptor): ThreadMoveTakes { ...(peer.moveRooms === true ? { rooms: true as const } : {}), ...(peer.moveOutsideWork === true ? { outsideWork: true as const } : {}), ...(peer.moveFamilies === true ? { families: true as const } : {}), + ...(peer.moveLinkLineage === true ? { linkLineage: true as const } : {}), }; } @@ -398,18 +401,31 @@ export function targetPreviewOf( // What the thread has going that this computer doesn't take (Part 3e): it // needs a newer Threadlines, whatever else it has. const notTaken = carry === undefined ? null : carryNotTaken(carry, takesOf(peer)); + // Another computer's agent started it, or a move brought it and no person + // here has taken it over yet: it goes back there only (Part 3f, (h)). + const origin = forThread?.thread.remoteOrigin ?? null; + const notHome = + origin !== null + ? origin.environmentId !== environmentId + ? remoteOriginElsewhereWords(origin.environmentLabel) + : null + : forThread === null + ? null + : fencedMoveRefusal(forThread.thread, { environmentId, label }); const refusal = peer.moves !== true ? `${peer.label} needs a newer Threadlines to take moved threads.` : peer.access === "off" ? `${peer.label} doesn't take work from this computer.` - : notTaken !== null - ? `Update Threadlines on ${peer.label} to move this thread: ${notTaken}.` - : noProject - ? `${peer.label} doesn't have this project.` - : peer.agents.length === 0 - ? `${peer.label} has no agent ready.` - : undefined; + : notHome !== null + ? notHome + : notTaken !== null + ? `Update Threadlines on ${peer.label} to move this thread: ${notTaken}.` + : noProject + ? `${peer.label} doesn't have this project.` + : peer.agents.length === 0 + ? `${peer.label} has no agent ready.` + : undefined; const notes = carry === undefined || refusal !== undefined ? [] @@ -490,6 +506,7 @@ export function targetPreviewOf( ...(refusal !== undefined && peer.moves === true && peer.access !== "off" && + notHome === null && notTaken === null && noProject ? { refusalCode: "no_project" as const } @@ -506,6 +523,16 @@ export function targetPreviewOf( ...(peer.moveStagedApproval === true ? { stagedApproval: true } : {}), ...(sessionOutcomes.length > 0 ? { sessionOutcomes } : {}), ...(roomAgents.length > 0 ? { roomAgents } : {}), + // A child moves there without its parent only when it stays its child + // across the link (Part 3f, (h)); else its whole family has to come. + ...(forThread !== null && + forThread.thread.parentThreadId !== null && + forThread.thread.attachedToParent && + peer.moveLinkLineage !== true + ? { + aloneRefusal: `Update Threadlines on ${peer.label} to move it without the thread that started it.`, + } + : {}), }; } @@ -836,6 +863,15 @@ const make = Effect.gen(function* () { } } const described = options.targets ?? (yield* describeTargets); + // Another computer's agent started it: it can only go back there, so a + // computer with no link to that one has nowhere to send it (Part 3f, (h)). + const origin = thread.remoteOrigin ?? null; + if ( + origin !== null && + !described.some((target) => target.environmentId === origin.environmentId) + ) { + refusal ??= `${remoteOriginElsewhereWords(origin.environmentLabel)} Link this computer to ${origin.environmentLabel} in Fleet first.`; + } // Sizes only: the files are read when the move packs them. const session = options.withSession === true ? yield* providers.exportNativeSession(thread.id) : undefined; @@ -949,6 +985,25 @@ const make = Effect.gen(function* () { if (parent === undefined && children.length === 0 && remoteChildren.length === 0) { return undefined; } + // A child's whole family, should it move with it: the parent and its children here. + const familySize = + parent === undefined + ? undefined + : yield* readMoveContext(parent.id).pipe( + Effect.map((context) => + context === null + ? undefined + : 1 + + context.view.threads.filter( + (entry) => + entry.parentThreadId === parent.id && + entry.attachedToParent && + entry.deletedAt === null && + entry.archivedAt === null, + ).length, + ), + Effect.orElseSucceed(() => 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) => @@ -976,7 +1031,15 @@ const make = Effect.gen(function* () { ), ); return { - ...(parent !== undefined ? { parent: { threadId: parent.id, title: parent.title } } : {}), + ...(parent !== undefined + ? { + parent: { + threadId: parent.id, + title: parent.title, + ...(familySize !== undefined ? { familySize } : {}), + }, + } + : {}), children: rows, remoteChildren, } satisfies NonNullable; @@ -1264,7 +1327,11 @@ const make = Effect.gen(function* () { readonly waitingForTarget?: boolean; } | { readonly kind: "abort"; readonly reason: string; readonly code: ThreadMoveAbortCode } - | { readonly kind: "complete"; readonly movedThreadId: ThreadId }, + | { + readonly kind: "complete"; + readonly movedThreadId: ThreadId; + readonly keptParent: boolean; + }, ) => Effect.gen(function* () { const createdAt = yield* nowIso; @@ -1307,6 +1374,7 @@ const make = Effect.gen(function* () { threadId, transferId, movedThreadId: step.movedThreadId, + ...(step.keptParent ? { keptParent: true as const } : {}), createdAt, }, ); @@ -1437,6 +1505,8 @@ const make = Effect.gen(function* () { yield* dispatchStep(threadId, transferId, { kind: "complete", movedThreadId: state.threadId, + // That computer's own word, over the link: it kept the parent (Part 3f, (h)). + keptParent: state.keptParent === true, }); } else if (state.status === "aborted") { yield* dispatchStep(threadId, transferId, { @@ -1527,6 +1597,12 @@ const make = Effect.gen(function* () { : familyManifestOf({ projects: model.projects, threads }, detail.value, moveFamily); const familyThreadIds = moveFamily === undefined ? undefined : familyThreadIdsOf(threads, moveFamily); + // Across the link its work came over (Part 3f, (h)), only for a + // computer that takes it back that way. + const linkLineage = + takes?.linkLineage === true && moveFamily === undefined + ? linkLineageOf(threads, detail.value, targetEnvironmentId) + : undefined; const source = { environmentId: descriptor.environmentId, environmentLabel: environment.currentLabel(), @@ -1546,6 +1622,7 @@ const make = Effect.gen(function* () { outsideWork, family, familyThreadIds, + linkLineage, }); } const { place, checkout } = yield* whereFrom(detail.value, project.workspaceRoot); @@ -1555,6 +1632,7 @@ const make = Effect.gen(function* () { outsideWork, family, familyThreadIds, + linkLineage, git, checkout, transferId, diff --git a/apps/server/src/moves/familyMove.ts b/apps/server/src/moves/familyMove.ts index c3ea3648b..3d19aba4d 100644 --- a/apps/server/src/moves/familyMove.ts +++ b/apps/server/src/moves/familyMove.ts @@ -6,8 +6,10 @@ * of its family. Pure: ThreadMoves reads the threads and asks these. */ import type { + EnvironmentId, OrchestrationThread, PeerMoveFamily, + PeerMoveLinkLineage, ThreadMoveFamily, ThreadMoveFamilyId, } from "@threadlines/contracts"; @@ -102,3 +104,38 @@ export const familyThreadIdsOf = ( family: ThreadMoveFamily, ): ReadonlySet => new Set(familyMembersOf(threads, family.id).map((member) => member.id)); + +/** + * What `thread`'s manifest says of the link its work came over, moving alone + * to `targetEnvironmentId` (docs/design/fleet.md, Part 3f, (h)), or nothing: + * + * - a thread another computer's agent started, going back to that computer: + * `home`, naming the thread there that started it; + * - a child moving without its parent: `remoteParent`, naming the parent, + * unless the parent is gone, frozen for its own move or moved away (then it + * lands as a thread of its own there). A parent whose move is only queued + * waits for this one, and if it moves later, this one is its child there. + * + * The other computer trusts neither beyond its own link and records. + */ +export function linkLineageOf( + threads: ReadonlyArray, + thread: OrchestrationThread, + targetEnvironmentId: EnvironmentId, +): PeerMoveLinkLineage | undefined { + const origin = thread.remoteOrigin ?? null; + if (origin !== null) { + return origin.environmentId === targetEnvironmentId + ? { home: { parentThreadId: origin.threadId } } + : undefined; + } + if (thread.parentThreadId === null || !thread.attachedToParent) return undefined; + if ((thread.move ?? thread.pendingMove)?.family !== undefined) return undefined; + // A parent whose own move is queued waits for this one (threadMoveRefusals), + // so it is still here when this lands; one frozen or moved away isn't. + const parent = threads.find((entry) => entry.id === thread.parentThreadId); + if (parent === undefined || parent.deletedAt !== null || (parent.move ?? null) !== null) { + return undefined; + } + return { remoteParent: { threadId: parent.id, title: parent.title } }; +} diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts index 8c51bd5ee..bdf7636e5 100644 --- a/apps/server/src/moves/moveExport.ts +++ b/apps/server/src/moves/moveExport.ts @@ -21,6 +21,7 @@ import type { OrchestrationThread, OrchestrationThreadActivity, PeerMoveFamily, + PeerMoveLinkLineage, PeerMoveGitManifest, PeerMoveManifest, PeerMovePart, @@ -499,6 +500,8 @@ export interface MoveExportInput { readonly family?: PeerMoveFamily | undefined; /** The family's members here, whose requests and reports keep their origin. */ readonly familyThreadIds?: ReadonlySet | undefined; + /** It moves across the link its work came over (Part 3f, (h)): see PeerMoveLinkLineage. */ + readonly linkLineage?: PeerMoveLinkLineage | undefined; } /** @@ -738,6 +741,7 @@ export function writeMoveExport( }, ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), + ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), }; yield* writeManifest(dir, manifest); return manifest; @@ -820,6 +824,7 @@ function writeSharerExport( }, ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), + ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), }; yield* writeManifest(input.dir, manifest); return manifest; @@ -1141,6 +1146,7 @@ export interface ScratchExportInput { /** Its family (Part 3f, (g)): a general chat has its own folder, so it shares none. */ readonly family?: PeerMoveFamily | undefined; readonly familyThreadIds?: ReadonlySet | undefined; + readonly linkLineage?: PeerMoveLinkLineage | undefined; } /** @@ -1255,6 +1261,7 @@ export function writeScratchExport( summary: { messageCount: history.messages.length, files: before.length }, ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), + ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), }; yield* writeManifest(input.dir, manifest); return manifest; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index d0e964b3b..2fe50db74 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -926,7 +926,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti : event.type === "thread.child-deliveries-cancelled" ? childRequestStateOn.deliveriesCancelled(state, event.payload.deliveryEpoch) : event.type === "thread.remote-child-updated" - ? childRequestStateOn.remoteChildUpdated(state, event.payload.child) + ? childRequestStateOn.remoteChildUpdated( + state, + event.payload.child, + event.payload.removed, + ) : event.type === "thread.remote-cancel-queued" ? childRequestStateOn.remoteCancelQueued(state, event.payload.cancel) : event.type === "thread.remote-cancels-delivered" diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index ca909b6ce..db805f1eb 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -19,6 +19,7 @@ import { ChildRequestId, type ChildRequestOutcome, type ChildThreadCheckout, + type EnvironmentId, EventId, MessageId, type OrchestrationChildRequest, @@ -567,6 +568,14 @@ export function decideChildSend( if (refusal !== null || child === null) { return refuse(refusal?.detail ?? "That thread is gone."); } + // A child frozen for its move takes nothing here (docs/design/fleet.md, + // Part 3f, (h)): a message written now would never reach it. + const childMove = child.move ?? null; + if (childMove !== null) { + return refuse( + `That thread is moving to ${childMove.target.label}. Send it the message once it's there.`, + ); + } if ( child.messages.some((message) => message.id === command.childMessageId) || parent.childRequests.open.some((request) => request.requestId === command.requestId) @@ -837,7 +846,7 @@ function decideRemoteChildSend( text: command.text, remote: { environmentId: remoteChild.environmentId, - label: remoteLabelOf(parent, remoteChild.environmentId), + label: remoteLabelOf(parent, remoteChild.environmentId, remoteChild.label), threadId: remoteChild.threadId, status: "sending", }, @@ -849,12 +858,11 @@ function decideRemoteChildSend( ]; } -/** The name a parent last knew a linked computer by. */ -const remoteLabelOf = (parent: OrchestrationThread, environmentId: string) => +/** The name a parent last knew a linked computer by: its newest request's, else its child's record's. */ +const remoteLabelOf = (parent: OrchestrationThread, environmentId: string, recorded: string) => parent.childRequests.open .toReversed() - .find((request) => request.remote?.environmentId === environmentId)?.remote?.label ?? - "the other computer"; + .find((request) => request.remote?.environmentId === environmentId)?.remote?.label ?? recorded; /** A request moved on (`thread.child-request.update`). */ export function decideChildRequestUpdate( @@ -1377,6 +1385,146 @@ export function decideParentAttachmentSet( ]; } +/** Activity on a child that moved to another computer without its parent. */ +export const MovedAloneActivityKind = "thread.moved-alone"; + +/** + * A child that moved to another computer without its parent + * (docs/design/fleet.md, Part 3f, (h)), on the computer it left, in the + * decision that records the move. Its copy here leaves the family, so the + * parent never counts it as a child here; the parent's requests for it + * settle as cancelled, with a note for its agent. When that computer kept it + * the parent's child across the link (`keptParent`, its answer over the + * link), the parent keeps it as a child there, as a thread it started there, + * and reaches it over the link from now on. + */ +export function movedAloneEvents( + readModel: OrchestrationReadModel, + baseFor: ChildEventBase, + child: OrchestrationThread, + moved: { + readonly target: { readonly environmentId: EnvironmentId; readonly label: string }; + readonly threadId: ThreadId; + readonly keptParent: boolean; + }, + at: string, +): ReadonlyArray { + if (child.parentThreadId === null || !child.attachedToParent) return []; + const parent = findThread(readModel, child.parentThreadId); + const label = moved.target.label; + const kept = moved.keptParent && parent !== null && parent.deletedAt === null; + const words = kept + ? `It's still a thread of '${parent.title}', which reaches it on ${label}.` + : `It's its own thread on ${label}, so the thread that started it can't reach it there.`; + return [ + { + ...baseFor(child.id), + type: "thread.parent-attachment-set", + payload: { + threadId: child.id, + attached: false, + attachmentEpoch: child.parentAttachmentEpoch + 1, + at, + }, + }, + { + ...baseFor(child.id), + type: "thread.activity-appended", + payload: { + threadId: child.id, + activity: { + id: EventId.make(`moved-alone:${child.id}:${child.parentAttachmentEpoch + 1}`), + tone: "info", + kind: MovedAloneActivityKind, + summary: words, + payload: { parentThreadId: child.parentThreadId, targetLabel: label, kept }, + turnId: null, + createdAt: at, + }, + }, + }, + ...(parent === null + ? [] + : settleOpenRequests( + readModel, + baseFor, + parent, + requestsFor(parent, child.id), + "cancelled", + at, + (titles) => + kept + ? `${quotedList(titles)} moved to ${label} before it answered. Send it the message again there.` + : `${quotedList(titles)} moved to ${label} as its own thread, so its answer won't come back to you.`, + )), + ...(kept + ? [ + { + ...baseFor(parent.id), + type: "thread.remote-child-updated" as const, + payload: { + threadId: parent.id, + child: { + environmentId: moved.target.environmentId, + label, + threadId: moved.threadId, + // The name RemoteChildReactor gives an asker it can't name. + handle: "Agent", + title: child.title, + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: at, + }, + updatedAt: at, + }, + }, + ] + : []), + ]; +} + +/** + * A thread this computer's agent started on another computer, back home + * (docs/design/fleet.md, Part 3f, (h)), on the parent, in the decision that + * imports it as the parent's child here: the record of it on that computer + * goes, and the requests still open for it there settle as cancelled (that + * computer settles its side when the thread leaves it). + */ +export function cameHomeEvents( + readModel: OrchestrationReadModel, + baseFor: ChildEventBase, + parent: OrchestrationThread, + from: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + at: string, +): ReadonlyArray { + const record = (parent.childRequests.remoteChildren ?? []).find( + (entry) => entry.environmentId === from.environmentId && entry.threadId === from.threadId, + ); + if (record === undefined) return []; + const open = parent.childRequests.open.filter( + (request) => + request.remote?.environmentId === from.environmentId && + (request.childThreadId === from.threadId || request.remote.threadId === from.threadId), + ); + return [ + ...settleOpenRequests( + readModel, + baseFor, + parent, + open, + "cancelled", + at, + (titles) => + `${quotedList(titles)} moved back to this computer before it answered from ${record.label}. Send it the message again here.`, + ), + { + ...baseFor(parent.id), + type: "thread.remote-child-updated", + payload: { threadId: parent.id, child: record, removed: true, updatedAt: at }, + }, + ]; +} + /** Activity on a child whose parent moved to another computer without it. */ export const ParentMovedAwayActivityKind = "thread.parent-moved-away"; diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 72fed9775..4afea7cb4 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -34,6 +34,7 @@ import { describe, expect, it } from "vite-plus/test"; import { decideOrchestrationCommand } from "./decider.ts"; import { createEmptyReadModel, projectEvent } from "./projector.ts"; +import { isLinkFenced } from "./linkFence.ts"; import { threadMoveGuardRefusal, threadMoveRefusals } from "./threadMoveDecisions.ts"; const now = "2026-10-22T10:00:00.000Z"; @@ -1764,7 +1765,8 @@ describe("a moved thread that moves on, or edits its goal before its agent knows commandId: nextCommandId(), threadId: ARRIVED, requestId: ThreadMoveRequestId.make("request-again"), - target: { environmentId: EnvironmentId.make("environment-pc"), label: "Windows PC" }, + // Back where it came from: still fenced, it goes nowhere else (Part 3f, (h)). + target: MAC_MINI, agent: modelSelection, mode: "when-done", requestedBy: { kind: "user" }, @@ -2349,7 +2351,7 @@ describe("a family moves together (Part 3f, (g))", () => { 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). + // Not before its parent, and not on its own to a computer that can't keep it its parent's. expect( (await apply(model, queueFor(CHILD, CHILD_REQUEST, { parentThreadId: THREAD }))).refusal, ).toContain("Its parent thread didn't move."); @@ -2775,3 +2777,689 @@ describe("a family moves together (Part 3f, (g))", () => { }); }); }); + +describe("across the link: a child alone, and a thread going home (Part 3f, (h))", () => { + const CHILD = ThreadId.make("thread-lone-child"); + const CHILD_REQUEST = ThreadMoveRequestId.make("request-lone-child"); + const CHILD_TRANSFER = ThreadMoveId.make("transfer-lone-child"); + const THERE = ThreadId.make("thread-there"); + const TAKES: ThreadMoveTakes = { threadState: true, families: true, linkLineage: true }; + const OLD_TAKES: ThreadMoveTakes = { threadState: true, families: true }; + const THIRD = { environmentId: EnvironmentId.make("environment-third"), label: "Linux box" }; + const PARENT_TURN = TurnId.make("turn-parent"); + + const withChild = async (model: OrchestrationReadModel) => + ( + await apply(model, { + type: "thread.create", + commandId: nextCommandId(), + threadId: CHILD, + projectId: PROJECT, + title: "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${CHILD}`, + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand) + ).model; + const queueFor = ( + threadId: ThreadId, + takes: ThreadMoveTakes = TAKES, + target: { readonly environmentId: EnvironmentId; readonly label: string } = MAC_MINI, + ): OrchestrationCommand => ({ + type: "thread.move.queue", + commandId: nextCommandId(), + threadId, + requestId: CHILD_REQUEST, + target, + agent: modelSelection, + mode: "when-done", + requestedBy: { kind: "user" }, + targetTakes: takes, + createdAt: now, + }); + /** Queued, quiesced and frozen: the child alone on its way to Mac mini. */ + const movedAlone = async (model: OrchestrationReadModel) => { + let next = (await apply(model, queueFor(CHILD))).model; + next = ( + await apply(next, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: CHILD, + requestId: CHILD_REQUEST, + createdAt: now, + }) + ).model; + const started = await apply(next, { + type: "thread.move.start", + commandId: nextCommandId(), + threadId: CHILD, + transferId: CHILD_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: CHILD_REQUEST, + targetTakes: TAKES, + createdAt: now, + }); + expect(started.refusal).toBeNull(); + return started.model; + }; + const complete = (keptParent: boolean): OrchestrationCommand => ({ + type: "thread.move.complete", + commandId: nextCommandId(), + threadId: CHILD, + transferId: CHILD_TRANSFER, + movedThreadId: THERE, + ...(keptParent ? { keptParent: true as const } : {}), + createdAt: now, + }); + /** The parent's agent at work in its turn, so it can send to its threads. */ + const parentWorking = (model: OrchestrationReadModel) => + project(model, "thread.session-set", { + threadId: THREAD, + session: { + threadId: THREAD, + status: "running", + providerName: "codex", + runtimeMode: "auto", + activeTurnId: PARENT_TURN, + lastError: null, + updatedAt: now, + }, + }); + const sendTo = (childThreadId: ThreadId, requestId: ChildRequestId): OrchestrationCommand => ({ + type: "thread.child.send", + commandId: nextCommandId(), + threadId: THREAD, + requestId, + from: { participantId: null }, + callerTurnId: PARENT_TURN, + childThreadId, + childMessageId: MessageId.make(`m-${requestId}`), + text: "Run the tests again", + createdAt: now, + }); + /** The parent asked its child something before it moved; the answer is owed. */ + const asked = (model: OrchestrationReadModel) => + project(model, "thread.child-request-submitted", { + threadId: THREAD, + request: { + requestId: ChildRequestId.make("ask-before"), + batchId: ChildRequestBatchId.make("ask-before"), + kind: "send", + from: { participantId: null }, + callerTurnId: PARENT_TURN, + deliveryEpoch: 0, + status: "awaiting_background", + childThreadId: CHILD, + childMessageId: MessageId.make("m-ask-before"), + createdAt: now, + }, + createdAt: now, + }); + + it("a child moves on its own only through the queue, to a computer that keeps it its parent's", async () => { + const model = await withChild(await seeded()); + expect((await apply(model, queueFor(CHILD, OLD_TAKES))).refusal).toContain( + "moves with the thread that started it", + ); + // A move that doesn't wait never crosses the link. + expect( + (await apply(model, { ...startMove(CHILD), targetTakes: TAKES } as OrchestrationCommand)) + .refusal, + ).toContain("belongs to the thread that started it"); + const queued = await apply(model, queueFor(CHILD)); + expect(queued.refusal).toBeNull(); + expect(threadOf(queued.model, CHILD).pendingMove?.family).toBeUndefined(); + }); + + it("the parent keeps a child that moved alone as its thread there, reaches it, and hears its answer", async () => { + let model = await movedAlone(await asked(await parentWorking(await withChild(await seeded())))); + // Its frozen copy here takes no message: it would never reach it. + expect((await apply(model, sendTo(CHILD, ChildRequestId.make("r-frozen")))).refusal).toContain( + "moving to Mac mini", + ); + ({ model } = await apply(model, complete(true))); + const copy = threadOf(model, CHILD); + expect(copy.attachedToParent).toBe(false); + expect(copy.activities.at(-1)).toMatchObject({ + kind: "thread.moved-alone", + summary: "It's still a thread of 'Fix the flaky test', which reaches it on Mac mini.", + }); + const parent = threadOf(model); + expect(parent.childRequests.remoteChildren).toEqual([ + expect.objectContaining({ + environmentId: MAC_MINI.environmentId, + label: "Mac mini", + threadId: THERE, + title: "Fix tests", + attachmentEpoch: 0, + }), + ]); + // What it was asked here won't come back from here: the agent is told. + expect(parent.childRequests.open).toEqual([]); + expect(parent.childRequests.pendingNotes.at(-1)?.text).toContain( + "moved to Mac mini before it answered", + ); + // thread_send reaches it over the link now. + const ask = ChildRequestId.make("r-there"); + ({ model } = await apply(model, sendTo(THERE, ask))); + expect(threadOf(model).childRequests.open).toEqual([ + expect.objectContaining({ + requestId: ask, + childThreadId: THERE, + remote: expect.objectContaining({ + environmentId: MAC_MINI.environmentId, + label: "Mac mini", + threadId: THERE, + }), + }), + ]); + // And its answer comes back into the parent. + const answered = await apply(model, { + type: "thread.child-request.settle", + commandId: nextCommandId(), + threadId: THREAD, + requestId: ask, + outcome: "answered", + reply: { messageId: MessageId.make("m-answer"), text: "All green", turnId: null }, + createdAt: now, + }); + expect(answered.refusal).toBeNull(); + expect(threadOf(answered.model).messages.at(-1)).toMatchObject({ + text: "All green", + fromThread: { threadId: THERE, environmentId: MAC_MINI.environmentId, kind: "report" }, + }); + }); + + it("a child that arrived as its own thread there leaves the family, and nothing records it there", async () => { + let model = await movedAlone(await withChild(await seeded())); + ({ model } = await apply(model, complete(false))); + expect(threadOf(model, CHILD).attachedToParent).toBe(false); + expect(threadOf(model, CHILD).activities.at(-1)?.summary).toBe( + "It's its own thread on Mac mini, so the thread that started it can't reach it there.", + ); + expect(threadOf(model).childRequests.remoteChildren ?? []).toEqual([]); + }); + + describe("a parent and its child moving alone never cross", () => { + const PARENT_REQUEST = ThreadMoveRequestId.make("request-parent-after"); + const PARENT_TRANSFER = ThreadMoveId.make("transfer-parent-after"); + const parentStep = ( + type: "thread.move.queue" | "thread.move.quiesce" | "thread.move.start", + ): OrchestrationCommand => + (type === "thread.move.queue" + ? { + type, + commandId: nextCommandId(), + threadId: THREAD, + requestId: PARENT_REQUEST, + target: MAC_MINI, + agent: modelSelection, + mode: "when-done", + requestedBy: { kind: "user" }, + targetTakes: TAKES, + createdAt: now, + } + : type === "thread.move.quiesce" + ? { + type, + commandId: nextCommandId(), + threadId: THREAD, + requestId: PARENT_REQUEST, + createdAt: now, + } + : { + type, + commandId: nextCommandId(), + threadId: THREAD, + transferId: PARENT_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: PARENT_REQUEST, + targetTakes: TAKES, + createdAt: now, + }) as OrchestrationCommand; + + it("a parent queued while its child moves alone waits for it, and goes once it settled", async () => { + let model = await movedAlone(await withChild(await seeded())); + const queued = await apply(model, parentStep("thread.move.queue")); + expect(queued.refusal).toBeNull(); + model = queued.model; + expect(threadOf(model).pendingMove?.waitsFor).toContainEqual({ + code: "background", + words: "when 'Fix tests' finishes moving", + }); + // Not stopped, nor frozen, while the child is under way: the freeze checks again. + expect((await apply(model, parentStep("thread.move.quiesce"))).refusal).toContain( + "Wait for this thread to finish", + ); + ({ model } = await apply(model, complete(true))); + ({ model } = await apply(model, parentStep("thread.move.quiesce"))); + const started = await apply(model, parentStep("thread.move.start")); + expect(started.refusal).toBeNull(); + expect(threadOf(started.model).move?.transferId).toBe(PARENT_TRANSFER); + }); + + /** The child works in its parent's folder; the parent has a message of the user's queued. */ + const sharingWithQueuedMessage = async () => { + let model = await withChild(await seeded()); + model = await project(model, "thread.meta-updated", { + threadId: CHILD, + worktreePath: "/worktrees/fix-flaky", + updatedAt: now, + }); + return project(model, "thread.follow-up-queued", { + threadId: THREAD, + followUp: { + messageId: MessageId.make("m-parent-queued"), + text: "And the docs", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }, + }); + }; + /** The model with the parent changed as `patch` says (what the projection would hold). */ + const withParent = (model: OrchestrationReadModel, patch: Record) => ({ + ...model, + threads: model.threads.map((thread) => + thread.id === THREAD ? ({ ...thread, ...patch } as unknown as typeof thread) : thread, + ), + }); + const sharedCheckoutWait = (model: OrchestrationReadModel) => + threadMoveRefusals(model, threadOf(model, CHILD), TAKES).filter( + (entry) => entry.code === "shared_checkout", + ); + + it("sharing a folder, the child still waits for what the parent really runs there", async () => { + let model = await sharingWithQueuedMessage(); + ({ model } = await apply(model, queueFor(CHILD))); + ({ model } = await apply(model, parentStep("thread.move.queue"))); + expect(sharedCheckoutWait(model)).toEqual([]); + // A command the parent runs in the terminal still changes the folder. + const commandRunning = withParent(model, { + commandRuns: [{ runId: "run-1", status: "running", source: { kind: "user" } }], + }); + expect(sharedCheckoutWait(commandRunning)).toHaveLength(1); + expect( + ( + await apply(commandRunning, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: CHILD, + requestId: CHILD_REQUEST, + createdAt: now, + }) + ).refusal, + ).toContain("finish"); + // So does background work its agent didn't wait on. + const backgroundWork = withParent(model, { + session: { + threadId: THREAD, + status: "ready", + providerName: "codex", + runtimeMode: "auto", + activeTurnId: null, + lastError: null, + pendingBackgroundTaskCount: 1, + awaitedBackgroundTaskCount: 0, + updatedAt: now, + }, + }); + expect(sharedCheckoutWait(backgroundWork)).toHaveLength(1); + }); + + it("sharing a folder, a child moving alone doesn't wait for the parent's message its own move holds", async () => { + let model = await sharingWithQueuedMessage(); + ({ model } = await apply(model, queueFor(CHILD))); + // While the parent can still send it, the child waits for it. + expect(threadMoveRefusals(model, threadOf(model, CHILD), TAKES)).toContainEqual( + expect.objectContaining({ code: "shared_checkout" }), + ); + // The parent queues its move, which holds that message and waits for the child. + ({ model } = await apply(model, parentStep("thread.move.queue"))); + expect(threadOf(model).pendingMove?.waitsFor).toContainEqual( + expect.objectContaining({ words: "when 'Fix tests' finishes moving" }), + ); + // So the child no longer waits for it: one of them goes. + expect(threadMoveRefusals(model, threadOf(model, CHILD), TAKES)).toEqual([]); + ({ model } = await apply(model, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: CHILD, + requestId: CHILD_REQUEST, + createdAt: now, + })); + expect( + ( + await apply(model, { + type: "thread.move.start", + commandId: nextCommandId(), + threadId: CHILD, + transferId: CHILD_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: CHILD_REQUEST, + targetTakes: TAKES, + createdAt: now, + }) + ).refusal, + ).toBeNull(); + }); + + it("a child doesn't start moving alone while its parent moves", async () => { + // The parent queued first: the child isn't queued alone. + let model = (await apply(await withChild(await seeded()), parentStep("thread.move.queue"))) + .model; + expect((await apply(model, queueFor(CHILD))).refusal).toContain( + "The thread that started it is moving to Mac mini", + ); + // The child queued first and the parent froze anyway (a race): the + // child's own freeze checks again and refuses. + model = (await apply(await withChild(await seeded()), queueFor(CHILD))).model; + model = ( + await apply(model, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: CHILD, + requestId: CHILD_REQUEST, + createdAt: now, + }) + ).model; + model = await project(model, "thread.move-started", { + threadId: THREAD, + transferId: PARENT_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + startedAt: now, + }); + expect( + ( + await apply(model, { + type: "thread.move.start", + commandId: nextCommandId(), + threadId: CHILD, + transferId: CHILD_TRANSFER, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: CHILD_REQUEST, + targetTakes: TAKES, + createdAt: now, + }) + ).refusal, + ).toContain("The thread that started it is moving to Mac mini"); + }); + }); + + describe("a thread another computer's agent started", () => { + const origin = (environmentPinned = true) => ({ + linkDeviceId: "device-mac-mini", + environmentId: MAC_MINI.environmentId, + environmentPinned, + environmentLabel: "Mac mini", + threadId: ThreadId.make("thread-on-mac"), + threadTitle: "Ship it", + }); + const startedThere = async (environmentPinned = true) => + ( + await apply(await seeded(), { + type: "thread.create", + commandId: nextCommandId(), + threadId: CHILD, + projectId: PROJECT, + title: "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${CHILD}`, + remoteOrigin: origin(environmentPinned), + createdAt: now, + } as OrchestrationCommand) + ).model; + + it("moves only back to that computer, over a link that proved it, never to a third", async () => { + const model = await startedThere(); + expect((await apply(model, queueFor(CHILD, TAKES, THIRD))).refusal).toContain( + "This thread was started by an agent on Mac mini, which still directs it. It can move back to Mac mini, not to another computer.", + ); + expect((await apply(model, queueFor(CHILD, OLD_TAKES))).refusal).toContain( + "Update Threadlines on Mac mini", + ); + expect((await apply(await startedThere(false), queueFor(CHILD))).refusal).toContain( + "can't confirm which computer that is", + ); + // The dialog asks about any computer: only the proof counts there. + expect( + threadMoveRefusals(model, threadOf(model, CHILD), TAKES, undefined, null).filter( + (entry) => entry.code === "remote_origin", + ), + ).toEqual([]); + const home = await apply(model, queueFor(CHILD)); + expect(home.refusal).toBeNull(); + // A move that doesn't wait never goes home either. + expect( + (await apply(model, { ...startMove(CHILD), targetTakes: TAKES } as OrchestrationCommand)) + .refusal, + ).toContain("This thread was started by an agent on Mac mini"); + }); + }); + + describe("arriving", () => { + const ARRIVED = ThreadId.make("thread-arrived-alone"); + const SOURCE = ThreadId.make("thread-on-mac"); + const importFrom = ( + from: { readonly environmentId: EnvironmentId; readonly label: string }, + extra: Record = {}, + ): OrchestrationCommand => + ({ + type: "thread.import", + commandId: nextCommandId(), + threadId: ARRIVED, + projectId: PROJECT, + title: "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/tests", + worktreePath: `/worktrees/${ARRIVED}`, + movedFrom: { ...from, threadId: SOURCE, movedAt: now }, + messages: [], + activities: [], + createdAt: now, + ...extra, + }) as OrchestrationCommand; + const remoteOrigin = { + linkDeviceId: "device-mac-mini", + environmentId: MAC_MINI.environmentId, + environmentPinned: true, + environmentLabel: "Mac mini", + threadId: ThreadId.make("thread-parent-on-mac"), + threadTitle: "Ship it", + }; + const personSends = (threadId: ThreadId): OrchestrationCommand => + ({ + type: "thread.turn.start", + commandId: nextCommandId(), + threadId, + message: { + messageId: MessageId.make("m-person"), + role: "user", + text: "Go", + attachments: [], + }, + sentFrom: { kind: "computer", place: "here" }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }) as OrchestrationCommand; + /** This computer's thread, which started SOURCE on Mac mini and still holds it there. */ + const holding = async ( + model: OrchestrationReadModel, + record: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } = { + environmentId: MAC_MINI.environmentId, + threadId: SOURCE, + }, + ) => { + let next = await project(model, "thread.remote-child-updated", { + threadId: THREAD, + child: { + ...record, + label: "Mac mini", + handle: "Agent", + title: "Fix tests", + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: now, + }, + updatedAt: now, + }); + next = await project(next, "thread.child-request-submitted", { + threadId: THREAD, + request: { + requestId: ChildRequestId.make("ask-there"), + batchId: ChildRequestBatchId.make("ask-there"), + kind: "send", + from: { participantId: null }, + callerTurnId: TurnId.make("turn-ask"), + deliveryEpoch: 0, + status: "running", + childThreadId: record.threadId, + childMessageId: MessageId.make("m-ask-there"), + text: "Check this", + remote: { ...MAC_MINI, threadId: record.threadId, status: "accepted" }, + createdAt: now, + }, + createdAt: now, + }); + return next; + }; + + it("a child that came alone stays its parent's, fenced for good: a person's message doesn't lift it", async () => { + let { model, refusal } = await apply(await seeded(), importFrom(MAC_MINI, { remoteOrigin })); + expect(refusal).toBeNull(); + const arrived = threadOf(model, ARRIVED); + expect(arrived.remoteOrigin).toEqual(remoteOrigin); + expect(arrived.parentThreadId).toBeNull(); + expect(arrived.movedFrom?.fenced).toBe(true); + expect(arrived.activities.at(-1)?.payload).toMatchObject({ + left: [ + "Started by 'Ship it' on Mac mini, which still directs it. Its agent can't use other threads, rooms or schedules here.", + ], + }); + ({ model } = await apply(model, personSends(ARRIVED))); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + expect(isLinkFenced(threadOf(model, ARRIVED))).toBe(true); + }); + + it("never keeps a parent a link can't prove, on another computer, or alongside a family", async () => { + const model = await seeded(); + expect( + ( + await apply( + model, + importFrom(MAC_MINI, { remoteOrigin: { ...remoteOrigin, environmentPinned: false } }), + ) + ).refusal, + ).toContain("proved its computer"); + // Forged: an identity other than the computer the move came from. + expect( + ( + await apply( + model, + importFrom(MAC_MINI, { + remoteOrigin: { ...remoteOrigin, environmentId: THIRD.environmentId }, + }), + ) + ).refusal, + ).toContain("computer it came from"); + expect( + ( + await apply(model, { + ...importFrom(MAC_MINI, { remoteOrigin }), + movedFrom: { ...MAC_MINI, threadId: SOURCE, movedAt: now, familyKey: "family-key" }, + } as OrchestrationCommand) + ).refusal, + ).toContain("moves on its own"); + expect( + ( + await apply( + model, + importFrom(MAC_MINI, { remoteOrigin, adopt: { parentThreadId: THREAD } }), + ) + ).refusal, + ).toContain("one parent"); + }); + + it("comes home under its parent only when that parent holds exactly this thread there", async () => { + const base = await holding(await seeded()); + const adopt = { adopt: { parentThreadId: THREAD } }; + // A forged home: this computer's thread never started that one. + expect( + ( + await apply(base, { + ...importFrom(MAC_MINI, adopt), + movedFrom: { ...MAC_MINI, threadId: ThreadId.make("thread-forged"), movedAt: now }, + } as OrchestrationCommand) + ).refusal, + ).toContain("doesn't hold this thread"); + // The same thread id, claimed over another computer's link. + expect((await apply(base, importFrom(THIRD, adopt))).refusal).toContain( + "doesn't hold this thread", + ); + // Never under a thread that isn't a top-level thread here, or that is moving. + const childHere = await withChild(base); + expect( + (await apply(childHere, importFrom(MAC_MINI, { adopt: { parentThreadId: CHILD } }))) + .refusal, + ).toContain("itself another thread's"); + expect( + (await apply((await apply(base, queueFor(THREAD))).model, importFrom(MAC_MINI, adopt))) + .refusal, + ).toContain("is moving"); + + let { model, refusal } = await apply(base, importFrom(MAC_MINI, adopt)); + expect(refusal).toBeNull(); + const home = threadOf(model, ARRIVED); + expect(home).toMatchObject({ parentThreadId: THREAD, attachedToParent: true }); + expect(home.remoteOrigin ?? null).toBeNull(); + expect(home.movedFrom?.fenced).toBe(true); + const parent = threadOf(model); + expect(parent.childRequests.remoteChildren ?? []).toEqual([]); + expect(parent.childRequests.open).toEqual([]); + expect(parent.childRequests.pendingNotes.at(-1)?.text).toContain( + "moved back to this computer before it answered from Mac mini", + ); + // Home is where the permission came from: the user here may take it over. + ({ model } = await apply(model, personSends(ARRIVED))); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + }); + + it("back home and still fenced, it goes nowhere but where it came from until a person writes", async () => { + let { model } = await apply( + await holding(await seeded()), + importFrom(MAC_MINI, { adopt: { parentThreadId: THREAD } }), + ); + // Alone, or as any thread: never on to a third computer while fenced. + expect((await apply(model, queueFor(ARRIVED, TAKES, THIRD))).refusal).toBe( + "Orchestration command invariant failed (thread.move.queue): This thread moved here from Mac mini, and until you send it a message here it can only move back to Mac mini.", + ); + expect((await apply(model, queueFor(ARRIVED, TAKES))).refusal).toBeNull(); + // A person here takes it over: the usual rules hold from now on. + ({ model } = await apply(model, personSends(ARRIVED))); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + // Its turn is something to wait for, never a refusal. + expect( + threadMoveRefusals(model, threadOf(model, ARRIVED), TAKES, undefined, THIRD).filter( + (entry) => entry.kind === "blocked", + ), + ).toEqual([]); + }); + }); +}); diff --git a/apps/server/src/orchestration/linkFence.ts b/apps/server/src/orchestration/linkFence.ts index 8c95c45a8..272333629 100644 --- a/apps/server/src/orchestration/linkFence.ts +++ b/apps/server/src/orchestration/linkFence.ts @@ -25,16 +25,19 @@ type TurnStartCommand = Extract, + thread: Pick, command: Pick< TurnStartCommand, "sentFrom" | "fromThread" | "fromOutside" | "scheduledTaskId" | "trigger" > & { readonly message: { readonly messageId: MessageId } }, ): boolean { if (thread.movedFrom?.fenced !== true || command.sentFrom === undefined) return false; + if ((thread.remoteOrigin ?? null) !== null) return false; if ( command.fromThread !== undefined || command.fromOutside !== undefined || diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 8cde1cb84..b750cb4f6 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -1047,7 +1047,7 @@ export function projectEvent( ).pipe( Effect.map((payload) => updateChildRequests(nextBase, payload.threadId, (state) => - childRequestStateOn.remoteChildUpdated(state, payload.child), + childRequestStateOn.remoteChildUpdated(state, payload.child, payload.removed), ), ), ); diff --git a/apps/server/src/orchestration/threadMoveCarry.ts b/apps/server/src/orchestration/threadMoveCarry.ts index 3b61dae3d..da16456dd 100644 --- a/apps/server/src/orchestration/threadMoveCarry.ts +++ b/apps/server/src/orchestration/threadMoveCarry.ts @@ -83,6 +83,11 @@ export interface ThreadMoveCarry { readonly rooms: boolean; readonly outsideWork: boolean; readonly families: boolean; + /** + * Another computer's agent started it (`remoteOrigin`): it can only go + * back to that computer, as its child there (Part 3f, (h)). + */ + readonly linkLineage: boolean; }; } @@ -93,6 +98,7 @@ export const ALL_MOVE_TAKES: ThreadMoveTakes = { rooms: true, outsideWork: true, families: true, + linkLineage: true, }; /** @@ -268,6 +274,7 @@ export function threadMoveCarry( family, needs: { families: family, + linkLineage: (thread.remoteOrigin ?? null) !== null, threadState: (goal !== null && goal.status !== "complete") || checkBacks.length > 0 || @@ -293,6 +300,9 @@ export function carryNotTaken( 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.linkLineage && takes?.linkLineage !== true) { + return "an agent on another computer started it"; + } 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 2f7b59e68..572d2c5d1 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -50,7 +50,7 @@ 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, leftBehindEvents } from "./childThreadDecisions.ts"; +import { cameHomeEvents, leftBehindEvents, movedAloneEvents } from "./childThreadDecisions.ts"; import { drainsWhileMoveWaits, interruptedOf, @@ -59,6 +59,7 @@ import { mergeInterrupted, sameInterrupted, threadMoveCarry, + waitingPlanOf, } from "./threadMoveCarry.ts"; import { SETTINGS_CHANGE_CANCELLED, @@ -86,6 +87,7 @@ export type ThreadMoveBlockCode = | "general_chat" | "room" | "remote_origin" + | "fenced" | "child" | "has_children" | "queued_messages" @@ -195,13 +197,16 @@ function foreignQueuedWords(entry: OrchestrationQueuedFollowUp): string { * 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. + * queued move's or move's when not given. `target` is the computer it goes + * to: the move's own when not given; null asks about any computer (the + * dialog, which then says per computer). */ export function threadMoveRefusals( readModel: ThreadMoveView, thread: OrchestrationThread, takes?: ThreadMoveTakes | null, family: ThreadMoveFamily | undefined = thread.pendingMove?.family ?? thread.move?.family, + target: ThreadMoveTarget | null = thread.pendingMove?.target ?? thread.move?.target ?? null, ): ReadonlyArray { const found: ThreadMoveRefusalEntry[] = []; // What rides along (docs/design/fleet.md, Part 3e) is refused only when the @@ -252,20 +257,30 @@ export function threadMoveRefusals( ), ); } - if ((thread.remoteOrigin ?? null) !== null) { - found.push( - blocked("remote_origin", "This thread was started from another computer, so it stays here."), - ); + // Another computer's agent started it: it goes back there, and nowhere + // else (Part 3f, (h), rule 2). + const origin = thread.remoteOrigin ?? null; + if (origin !== null) { + const refusal = remoteOriginMoveRefusal(origin, takes, target); + if (refusal !== null) found.push(blocked("remote_origin", refusal)); + } else { + // What a move brought works behind the fence until a person here takes + // it over; until then it goes back where it came from, and nowhere else, + // so no chain of moves carries another computer's work to a third. + const refusal = fencedMoveRefusal(thread, target); + if (refusal !== null) found.push(blocked("fenced", refusal)); } - // A child moves only with its parent (Part 3f, (g)): its move names the + // A child moves 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. + // under way, or done). Or it moves alone (Part 3f, (h)) to a computer that + // keeps it its parent's child across the link. if (thread.parentThreadId !== null && thread.attachedToParent) { const withParent = takesFamilies && family?.parentThreadId === thread.parentThreadId && parentHoldsFamily(readModel, family); - if (!withParent) { + const alone = family === undefined && takes?.linkLineage === true; + if (!withParent && !alone) { found.push( blocked( "child", @@ -277,6 +292,40 @@ export function threadMoveRefusals( ), ); } + // Alone, never while its parent moves (Part 3f, (h)): the parent would + // leave it behind on its way out while it lands there as the parent's + // child. A parent that queued after this child's own move waits for it + // instead (below), so the earlier move goes first. + if (family === undefined) { + const parent = readModel.threads.find((entry) => entry.id === thread.parentThreadId); + const parentMove = parent?.move ?? null; + const ownMove = (thread.pendingMove ?? null) !== null || (thread.move ?? null) !== null; + const parentMoving = + (parentMove !== null && parentMove.movedAway === undefined) || + ((parent?.pendingMove ?? null) !== null && !ownMove); + if (parent !== undefined && parent.deletedAt === null && parentMoving) { + const label = (parent.move ?? parent.pendingMove)?.target.label ?? "another computer"; + found.push( + blocked( + "child", + `The thread that started it is moving to ${label}. Move this one once that's done, or with it.`, + ), + ); + } + } + } + // A child of this thread moving on its own: this thread goes once it has + // (Part 3f, (h)), so it never leaves the child behind mid-move. No wait + // code of its own (a closed set): `background`, with its own words. + const childMovingAlone = readModel.threads.find( + (candidate) => + candidate.parentThreadId === thread.id && + candidate.attachedToParent && + candidate.deletedAt === null && + movesAlone(candidate), + ); + if (childMovingAlone !== undefined) { + found.push(wait("background", `when '${childMovingAlone.title}' finishes moving`)); } const hasLocalChildren = readModel.threads.some( (candidate) => @@ -354,6 +403,48 @@ export function threadMoveRefusals( } // What goes away on its own. + found.push( + ...workWaits(thread, { + rooms: takesRooms, + families: takesFamilies, + sendable: thread.queuedFollowUps ?? [], + }), + ); + // Another thread at work in the same checkout could change the files while + // 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. + const checkout = checkoutOf(readModel, thread); + const sharedCheckoutBusy = readModel.threads.some( + (candidate) => + candidate.id !== thread.id && + candidate.deletedAt === null && + (candidate.move ?? null) === null && + checkoutOf(readModel, candidate) === checkout && + busyInFolder(candidate), + ); + if (sharedCheckoutBusy) found.push(wait("shared_checkout")); + return found; +} + +/** + * What `thread` is doing now that goes away on its own (docs/design/fleet.md, + * Parts 3b and 3f), as its move's waits: a turn and what it asks of the user, + * side answers, background work, a command in the terminal, a workflow, a + * voice chat, and (`rooms`, `families`) its agents' requests of each other + * and the threads it started, with the queued messages among `sendable` that + * keep those going. The one list a thread's own move waits on and the one + * a move in the same folder waits on (`busyInFolder`), so the two can't drift. + */ +function workWaits( + thread: OrchestrationThread, + options: { + readonly rooms: boolean; + readonly families: boolean; + /** Its queued messages that can still be sent. */ + readonly sendable: ReadonlyArray; + }, +): ThreadMoveRefusalEntry[] { + const found: ThreadMoveRefusalEntry[] = []; const session = thread.session; if ( thread.latestTurn?.state === "running" || @@ -369,7 +460,7 @@ export function threadMoveRefusals( found.push(wait("question")); } if (liveSideTurns(thread).length > 0) found.push(wait("side_turn")); - if (takesRooms) { + if (options.rooms) { const open = thread.agentRequests.open; // An invite waiting for the user's answer; the rest are agents at work. if (open.some((request) => request.status === "awaiting_user")) { @@ -377,21 +468,21 @@ export function threadMoveRefusals( } if ( open.some((request) => request.status !== "awaiting_user") || - carry.foreignQueued.some(isRoomAgentQueued) + options.sendable.some(isRoomAgentQueued) ) { 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) { + if (options.families) { 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)) + options.sendable.some((entry) => isFamilyQueued(thread, entry)) ) { found.push(wait("background", FAMILY_WAIT_WORDS)); } @@ -413,36 +504,97 @@ export function threadMoveRefusals( found.push(wait("workflow_run")); } 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. 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 && - busyThere(candidate), - ); - if (sharedCheckoutBusy) found.push(wait("shared_checkout")); return found; } +/** + * Whether another thread working in a folder could still change its files + * (the `shared_checkout` wait): anything its own move would wait on + * (workWaits, room and family work included), and the queued messages and + * waiting plan that can still start a turn. What its own queued move holds + * back doesn't count: its user's queued messages and its plan wait for that + * move (the guard refuses them); while it waits (`waiting`) a room agent's + * hand-off and the family's requests and answers still drain, and from + * `quiescing` on nothing queued is sent. Counting what is held would let two + * moves wait on each other for good: two family members sharing a folder + * (Part 3f, (g)), or a parent waiting for its child's own move while the + * child waits for the parent's held message (Part 3f, (h)). + */ +function busyInFolder(thread: OrchestrationThread): boolean { + const pending = thread.pendingMove ?? null; + const queued = thread.queuedFollowUps ?? []; + const sendable = + pending === null + ? queued + : pending.stage === "waiting" + ? queued.filter((entry) => drainsWhileMoveWaits(thread, entry)) + : []; + return ( + sendable.length > 0 || + (pending === null && waitingPlanOf(thread) !== null) || + workWaits(thread, { rooms: true, families: true, sendable }).length > 0 + ); +} + +/** + * Why a thread another computer's agent started (`origin`) can't move to + * `target`, or null (docs/design/fleet.md, Part 3f, (h), rule 2): it goes + * only back to that computer, only when the link proved which computer that + * is (`environmentPinned`), and only to one that takes it back as its + * child. A null `target` asks whether it can go anywhere: the home check is + * then the dialog's, per computer. + */ +export function remoteOriginMoveRefusal( + origin: NonNullable, + takes: ThreadMoveTakes | null | undefined, + target: ThreadMoveTarget | null, +): string | null { + const home = origin.environmentLabel; + if (origin.environmentPinned !== true) { + return `This thread was started by an agent on ${home}, and this computer's link can't confirm which computer that is, so it stays here.`; + } + if (target === null) return null; + if (target.environmentId !== origin.environmentId) return remoteOriginElsewhereWords(home); + if (takes?.linkLineage !== true) { + return `This thread was started by an agent on ${home}. Update Threadlines on ${target.label} to move it back there.`; + } + return null; +} + +/** + * Why a thread a move brought here, still behind the fence (`movedFrom.fenced`: + * no person here has sent it a message yet), can't move to `target`, or null + * (docs/design/fleet.md, Part 3f, (h)): it goes back to the computer it came + * from, and nowhere else. Once a person here takes it over, the usual rules + * hold. A null `target` asks about any computer: the dialog says per computer. + */ +export function fencedMoveRefusal( + thread: Pick, + target: ThreadMoveTarget | null, +): string | null { + const from = thread.movedFrom ?? null; + if (from === null || from.fenced !== true || target === null) return null; + return target.environmentId === from.environmentId ? null : fencedElsewhereWords(from.label); +} + +/** The words for a fenced moved thread, moving anywhere but back where it came from. */ +export const fencedElsewhereWords = (from: string) => + `This thread moved here from ${from}, and until you send it a message here it can only move back to ${from}.`; + +/** Whether a child is moving on its own (Part 3f, (h)): queued or under way, not in a family. */ +const movesAlone = (thread: Pick) => { + const pending = thread.pendingMove ?? null; + const move = thread.move ?? null; + return ( + (pending !== null && pending.family === undefined) || + (move !== null && move.family === undefined && move.movedAway === undefined) + ); +}; + +/** The words for a thread another computer's agent started, moving anywhere but home. */ +export const remoteOriginElsewhereWords = (home: string) => + `This thread was started by an agent on ${home}, which still directs it. It can move back to ${home}, not to another computer.`; + /** * 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 @@ -490,8 +642,9 @@ export function threadMoveRefusal( thread: OrchestrationThread, takes?: ThreadMoveTakes | null, family?: ThreadMoveFamily, + target?: ThreadMoveTarget | null, ): string | null { - const refusals = threadMoveRefusals(readModel, thread, takes, family); + const refusals = threadMoveRefusals(readModel, thread, takes, family, target); const block = firstMoveBlock(refusals); if (block !== null) return block.words; const first = refusals[0]; @@ -724,15 +877,16 @@ export function decideMoveStart( } // 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); + // any is refused as before; nor does it cross the link its work came + // over (Part 3f, (h)). Both move through the queue. + const { families: _families, linkLineage: _linkLineage, ...alone } = takes ?? {}; + const refusal = threadMoveRefusal(readModel, thread, alone, undefined, command.target); if (refusal !== null) return refuse(refusal); } else { if (pending === null || pending.requestId !== queuedRequestId) { return refuse("That queued move was cancelled or replaced."); } - const refusals = threadMoveRefusals(readModel, thread, takes); + const refusals = threadMoveRefusals(readModel, thread, takes, undefined, command.target); const block = firstMoveBlock(refusals); if (block !== null) return refuse(block.words); if (refusals.length > 0) return refuse(BUSY_WORDS); @@ -927,7 +1081,13 @@ export function decideMoveQueue( ) { return refuse("That thread didn't start this one."); } - const refusals = threadMoveRefusals(readModel, thread, command.targetTakes, command.family); + const refusals = threadMoveRefusals( + readModel, + thread, + command.targetTakes, + command.family, + command.target, + ); 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 @@ -1308,7 +1468,9 @@ export function decideMoveAbort( * 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)). + * same decision (docs/design/fleet.md, Part 3f, (g)). A child that moved + * without its parent leaves the family here, and stays the parent's child + * on that computer when that computer kept it so (`keptParent`, Part 3f, (h)). */ export function decideMoveComplete( readModel: OrchestrationReadModel, @@ -1348,6 +1510,19 @@ export function decideMoveComplete( }, ...readOnlyCopyEvents(thread, command.createdAt, baseFor), ...leftBehind, + ...(move.family === undefined + ? movedAloneEvents( + readModel, + baseFor, + thread, + { + target: move.target, + threadId: command.movedThreadId, + keptParent: command.keptParent === true, + }, + command.createdAt, + ) + : []), ]; } @@ -1397,6 +1572,9 @@ function readOnlyCopyEvents( /** The "Moved here" line's word on the fence a moved thread works behind (ThreadMovedFrom.fenced). */ const MOVED_FENCE_WORDS = "Its agent can't use other threads, rooms or schedules here until you send it a message."; +/** The same for a child that stays its parent's across the link: fenced for good (Part 3f, (h)). */ +const remoteParentFenceWords = (origin: NonNullable) => + `Started by '${origin.threadTitle}' on ${origin.environmentLabel}, which still directs it. Its agent can't use other threads, rooms or schedules here.`; /** * A moved thread arriving: created with its history and the boundary that @@ -1420,6 +1598,8 @@ export function decideThreadImport( if (roomRefusal !== null) return refuse(roomRefusal); const familyRefusal = importedFamilyRefusal(readModel, command); if (familyRefusal !== null) return refuse(familyRefusal); + const linkRefusal = importedLinkLineageRefusal(readModel, command); + if (linkRefusal !== null) return refuse(linkRefusal); // 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). @@ -1438,6 +1618,7 @@ export function decideThreadImport( return refuse("A message it brings is already another thread's here."); } const lineage = command.lineage; + const adopt = command.adopt; const base = () => baseFor(command.threadId); const created: PlannedEvent = { ...base(), @@ -1460,6 +1641,12 @@ export function decideThreadImport( attachedToParent: true, } : {}), + // Back home, under the thread that started it there (Part 3f, (h)). + ...(adopt !== undefined + ? { parentThreadId: adopt.parentThreadId, attachedToParent: true } + : {}), + // Still its parent's on the computer it came from, fenced for good (Part 3f, (h)). + ...(command.remoteOrigin !== undefined ? { remoteOrigin: command.remoteOrigin } : {}), // 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. @@ -1535,7 +1722,12 @@ export function decideThreadImport( payload: { threadId: command.threadId, activity: { ...activity, turnId: null } }, })); const arrival = command.arrival; - const left = [...(arrival?.left ?? []), MOVED_FENCE_WORDS]; + const left = [ + ...(arrival?.left ?? []), + command.remoteOrigin !== undefined + ? remoteParentFenceWords(command.remoteOrigin) + : MOVED_FENCE_WORDS, + ]; const boundary: PlannedEvent = { ...base(), type: "thread.activity-appended", @@ -1564,7 +1756,86 @@ export function decideThreadImport( }, }, }; - return [created, ...room, ...messages, ...activities, ...importedState(command, base), boundary]; + // Home again: the parent's record of it on the computer it came from goes. + const adoptedBy = + adopt === undefined + ? undefined + : readModel.threads.find((thread) => thread.id === adopt.parentThreadId); + const cameHome = + adoptedBy === undefined + ? [] + : cameHomeEvents( + readModel, + baseFor, + adoptedBy, + { environmentId: command.movedFrom.environmentId, threadId: command.movedFrom.threadId }, + command.createdAt, + ); + return [ + created, + ...room, + ...messages, + ...activities, + ...importedState(command, base), + boundary, + ...cameHome, + ]; +} + +/** + * Why a thread moving across the link its work came over can't land as it + * says, or null (docs/design/fleet.md, Part 3f, (h)). Both kinds move on + * their own, never in a family. `remoteOrigin` keeps it the child of a + * thread on the computer it came from, only for a link that proved which + * computer that is. `adopt` puts it under one of this computer's threads + * only when that thread already holds exactly this thread, on exactly that + * computer, as its child: a linked computer can never attach a thread under + * one of this computer's own. + */ +function importedLinkLineageRefusal( + readModel: OrchestrationReadModel, + command: CommandOf<"thread.import">, +): string | null { + const origin = command.remoteOrigin; + const adopt = command.adopt; + if (origin === undefined && adopt === undefined) return null; + if (origin !== undefined && adopt !== undefined) return "A thread lands under one parent."; + if ( + command.lineage !== undefined || + command.movedFrom.familyKey !== undefined || + command.worktreeOrigin !== undefined + ) { + return "A thread that moves across its link moves on its own."; + } + if (origin !== undefined) { + if (origin.environmentPinned !== true) { + return "Only a link that proved its computer can keep a thread's parent."; + } + if (origin.environmentId !== command.movedFrom.environmentId) { + return "It can only stay the child of a thread on the computer it came from."; + } + return null; + } + if (adopt === undefined) return null; + const parent = readModel.threads.find((entry) => entry.id === adopt.parentThreadId); + if (parent === undefined || parent.deletedAt !== null) { + return "The thread that started it isn't here."; + } + if ((parent.move ?? null) !== null || (parent.pendingMove ?? null) !== null) { + return "The thread that started it is moving."; + } + if (parent.parentThreadId !== null && parent.attachedToParent) { + return "The thread that started it is itself another thread's."; + } + if (parent.projectId !== command.projectId) { + return "The thread that started it is in another project."; + } + const held = (parent.childRequests.remoteChildren ?? []).some( + (entry) => + entry.environmentId === command.movedFrom.environmentId && + entry.threadId === command.movedFrom.threadId, + ); + return held ? null : "The thread that started it doesn't hold this thread."; } /** diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 97edd1e19..bb2cf5e35 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -1153,6 +1153,101 @@ describe("ChatView (full app): moving a thread to another computer", () => { } }); + it("a child moves just itself, staying its parent's, or its whole family", async () => { + setPrimaryLinksSnapshot( + fleetLinksSnapshot({ + outbound: [fleetOutboundLink(FLEET_OFFLINE_ENVIRONMENT_ID, "Mac mini")], + }), + ); + const macMini = FLEET_MOVE_PREVIEW.targets[1]!; + const parent = ThreadId.make("thread-ship-it"); + const queues: Array = []; + let aloneRefusal: string | undefined; + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-move-child" as MessageId, + targetText: "move child", + }), + configureFixture: withThreadMoveQueueFixture, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.movesPreview) { + return { + ...FLEET_MOVE_PREVIEW, + family: { + parent: { threadId: parent, title: "Ship it", familySize: 4 }, + children: [], + remoteChildren: [], + }, + targets: [{ ...macMini, ...(aloneRefusal !== undefined ? { aloneRefusal } : {}) }], + } satisfies ThreadMovePreview; + } + if (body._tag === WS_METHODS.movesQueue) { + queues.push(body); + return { requestId: QUEUED_REQUEST_ID }; + } + return undefined; + }, + }); + + const openDialog = async () => { + await openCommandPaletteFromTrigger(); + await page + .getByTestId("command-palette") + .getByText("Move to another computer", { exact: true }) + .click(); + return page.getByTestId("thread-move-dialog"); + }; + + try { + await waitForServerConfigToApply(); + await saveMacMini("connected"); + let dialog = await openDialog(); + // Just this thread by default: it stays the parent's, which can still send to it. + await expect + .element(dialog.getByTestId("thread-move-child-alone-detail")) + .toHaveTextContent( + "It stays a thread of Ship it on Local environment, which can still send to it.", + ); + await expect + .element(dialog.getByTestId("thread-move-child-family-label")) + .toHaveTextContent("Move its whole family (4 threads)"); + await dialog.getByTestId("thread-move-confirm").click(); + await expect.element(page.getByTestId("thread-move-dialog")).not.toBeInTheDocument(); + expect(queues.at(-1)).toEqual( + expect.objectContaining({ + threadId: THREAD_ID, + targetEnvironmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + }), + ); + + // The whole family: the parent is queued, with every thread it started. + dialog = await openDialog(); + await dialog.getByTestId("thread-move-child-family").click(); + await dialog.getByTestId("thread-move-confirm").click(); + await expect.element(page.getByTestId("thread-move-dialog")).not.toBeInTheDocument(); + expect(queues.at(-1)).toEqual({ + _tag: WS_METHODS.movesQueue, + threadId: parent, + targetEnvironmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + mode: "when-done", + }); + + // A computer that can't keep it its parent's takes only the family, and says why. + aloneRefusal = + "Update Threadlines on Mac mini to move it without the thread that started it."; + dialog = await openDialog(); + await expect + .element(dialog.getByTestId("thread-move-child-alone-detail")) + .toHaveTextContent(aloneRefusal); + await dialog.getByTestId("thread-move-confirm").click(); + await expect.element(page.getByTestId("thread-move-dialog")).not.toBeInTheDocument(); + expect(queues.at(-1)).toEqual(expect.objectContaining({ threadId: parent })); + } finally { + await mounted.cleanup(); + } + }); + it("says when a waiting move goes, holds new messages, and cancels the move it shows", async () => { setPrimaryLinksSnapshot( fleetLinksSnapshot({ diff --git a/apps/web/src/components/ThreadMoveDialogContent.tsx b/apps/web/src/components/ThreadMoveDialogContent.tsx index 0bed973a9..82ce0f851 100644 --- a/apps/web/src/components/ThreadMoveDialogContent.tsx +++ b/apps/web/src/components/ThreadMoveDialogContent.tsx @@ -28,6 +28,7 @@ import { import { cn } from "../lib/utils"; import { selectSidebarThreadSummaryByRef, useStore } from "../store"; import { + describeChildFamilyMove, describeFamilyComing, describeRemoteChildrenStaying, describeThreadMoveLanding, @@ -99,6 +100,8 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread const [roomPicks, setRoomPicks] = useState(NO_ROOM_PICKS); // A parent's children the user unticked: they stay here as their own threads. const [staying, setStaying] = useState>(() => new Set()); + // A child: it moves on its own (staying its parent's child), or its whole family moves. + const [pickedChildMove, setChildMove] = useState("alone"); const [pickedMode, setMode] = useState("when-done"); const [starting, setStarting] = useState(false); const [startError, setStartError] = useState(null); @@ -179,6 +182,16 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread const coming = (family?.children ?? []).filter( (child) => child.refusal === undefined && !staying.has(child.threadId), ); + // A child (Part 3f, (h)): on its own when that computer keeps it its + // parent's child, else with its whole family. + const parent = family?.parent; + const childMove: ChildMoveChoice = + parent === undefined + ? "alone" + : target?.aloneRefusal !== undefined + ? "family" + : pickedChildMove; + const withFamily = parent !== undefined && childMove === "family"; const canMove = preview !== null && preview.refusal === undefined && @@ -194,7 +207,15 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread try { const client = requireThreadMovesClient(threadRef.environmentId, computerLabel); const input = { threadId: threadRef.threadId, targetEnvironmentId: target.environmentId }; - if (queues) { + if (queues && withFamily) { + // The parent with every thread it started: the server's whole family, + // each with the agent that computer suggests. + await client.queue({ + threadId: parent.threadId, + targetEnvironmentId: target.environmentId, + mode: working ? mode : "when-done", + }); + } else if (queues) { await client.queue({ ...input, ...(unreachable || agentSelection === null ? {} : { agent: agentSelection }), @@ -367,6 +388,19 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread : null} )} + {parent !== undefined && queues ? ( + { + setChildMove(next); + setStartError(null); + }} + /> + ) : null} {family !== undefined && (family.children.length > 0 || family.remoteChildren.length > 0) ? ( ["parent"]>; + readonly hereLabel: string; + readonly target: ThreadMoveTargetPreview; + readonly choice: ChildMoveChoice; + readonly disabled: boolean; + readonly onChange: (choice: ChildMoveChoice) => void; +}) { + const choices: ReadonlyArray<{ + readonly value: ChildMoveChoice; + readonly label: string; + readonly detail: string; + readonly refusal: string | null; + }> = [ + { + value: "alone", + label: "Move just this thread", + detail: `It stays a thread of ${parent.title} on ${hereLabel}, which can still send to it.`, + refusal: target.aloneRefusal ?? null, + }, + { + value: "family", + label: describeChildFamilyMove(parent.familySize), + detail: `${parent.title} and the threads it started move to ${target.label} together.`, + refusal: null, + }, + ]; + return ( + onChange(value as ChildMoveChoice)} + aria-label="What moves" + className="gap-0.5" + data-testid="thread-move-child" + > + {choices.map((entry) => ( + + ))} + + ); +} + /** * A parent's family (docs/design/fleet.md, Part 3f, (g)): its threads here, * ticked to come along, each unticked or unable to come staying here as its diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 3632e97fc..a8461ae4e 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -3735,7 +3735,7 @@ function applyEnvironmentOrchestrationEvent( // Children on linked computers (docs/design/fleet.md), kept on the parent. case "thread.remote-child-updated": return updateChildRequestState(state, event.payload.threadId, (current) => - childRequestStateOn.remoteChildUpdated(current, event.payload.child), + childRequestStateOn.remoteChildUpdated(current, event.payload.child, event.payload.removed), ); case "thread.remote-cancel-queued": diff --git a/apps/web/src/threadMove.ts b/apps/web/src/threadMove.ts index c02a86fc2..76377188b 100644 --- a/apps/web/src/threadMove.ts +++ b/apps/web/src/threadMove.ts @@ -992,6 +992,16 @@ export function withMoveFamilies( return [...out]; } +/** + * A child's choice to move with its family (docs/design/fleet.md, Part 3f, + * (h)): "Move its whole family (4 threads)", the count when the server gave it. + */ +export function describeChildFamilyMove(familySize: number | undefined): string { + return familySize === undefined + ? "Move its whole family" + : `Move its whole family (${familySize} threads)`; +} + /** "Its 3 threads move with it", for the threads of a family ticked to come. */ export function describeFamilyComing(count: number): string { return count === 0 diff --git a/docs/design/fleet.md b/docs/design/fleet.md index e52ec4bcc..3b2c7440b 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1543,6 +1543,21 @@ These win over the text above where they differ. - Present: exactly the listed threads move, and the unlisted children stay behind under the rule above. - New clients always send it. +### Build notes for "across the link" (Nov 17) + +Where the build differs from the text above, and why. + +1. **Its own capability.** `PeerDescriptor.moveLinkLineage` and `targetTakes.linkLineage`, not `moveFamilies`: a computer that already takes families would read a lone child's manifest as a family member and wait for a parent that never comes. +2. **Its own manifest field.** `PeerMoveManifest.linkLineage { remoteParent? | home? }` (exactly one, never with `family`), not `family.remoteParent` / `family.home`: `PeerMoveFamily.id` stays required, and nothing in the family code path sees these moves. +3. **No new event.** "Moving back home" removes the parent's record with `thread.remote-child-updated` and a new optional `removed: true`, not a new `thread.remote-child-removed`: the event union is closed to clients that decode it. An older client keeps showing the record until it reloads. +4. **Nothing new on the pending move.** A child queued without a family, to a computer that takes `linkLineage`, is a child moving alone. The export names `remoteParent` only when the parent is here and not moving; the other computer's committed answer says whether it kept the parent (`PeerMoveState.keptParent`, read from the thread it wrote), and `thread.move.complete` carries that into the decision that writes the parent's record. +5. **The child's dialog.** "Move its whole family" queues the parent with no `familySelection` (the server's whole family). A computer without `linkLineage` disables "Move just this thread" with why (`ThreadMoveTargetPreview.aloneRefusal`). +6. **Moves that don't wait** (`moves.start`, older apps) never cross the link, for a child or a thread going home. +7. **A fenced thread goes only back where it came from** (review fix). A thread a move brought, still fenced (`movedFrom.fenced`), may move only to `movedFrom.environmentId` until a person here sends it a message, for every kind of move (single, batch, alone, family). Without this, a link-started thread that came home as a local child could move on to a third computer with nobody having taken it over. +8. **A parent and its child moving alone never cross** (review fix). A parent's move waits (`background`, "when '' finishes moving") while a child of it has a move of its own queued or under way; the freeze decision checks it again. A child doesn't start moving alone while its parent's move is under way, nor queue while its parent's is queued. Otherwise the parent's move could leave behind a child that lands on the other computer as the parent's child. +9. **What a queued move holds isn't work in a shared folder** (review fix). A thread whose own move is queued holds its user's messages and its plan (the guard refuses them), so the shared-folder wait counts only what still runs there: everything that thread's own move would wait on (a turn and its approvals and questions, side answers, either background count, a command in the terminal, a workflow, a voice chat, the room's and the family's open requests), one list for both (`workWaits`), and while it waits (`waiting`) the room's and the family's messages that still drain. Otherwise a parent waiting for its child's own move, in the same folder, and the child waiting for the parent's held message, would wait on each other for good. +10. **A queued parent keeps its lone child** (review fix). The export names `remoteParent` whenever the parent is here and not frozen or moved away. A parent whose own move is queued waits for the child, so if it cancels the child is still its child there, and if it moves later the child is one of its threads on another computer, which stay, named. + ## Part 4: The rail and the Fleet page ### Rail diff --git a/packages/contracts/src/moves.ts b/packages/contracts/src/moves.ts index aeb1833e8..bb554667b 100644 --- a/packages/contracts/src/moves.ts +++ b/packages/contracts/src/moves.ts @@ -5,6 +5,7 @@ import { EnvironmentId, IsoDateTime, NonNegativeInt, + PositiveInt, ThreadId, ThreadMoveBatchId, ThreadMoveId, @@ -121,6 +122,12 @@ export const ThreadMoveTargetPreview = Schema.Struct({ notes: Schema.optional(Schema.Array(ThreadMoveNote)), /** A room (ThreadMovePreview.room): each of its agents on this computer. */ roomAgents: Schema.optional(Schema.Array(ThreadMoveRoomAgentTarget)), + /** + * A child (ThreadMovePreview.family.parent): why it can't move there + * without its parent, which then has to come along ("Update Threadlines on + * Windows PC to move it on its own."). Absent: it can. + */ + aloneRefusal: Schema.optional(TrimmedNonEmptyString), }); export type ThreadMoveTargetPreview = typeof ThreadMoveTargetPreview.Type; @@ -171,11 +178,19 @@ export const ThreadMovePreview = Schema.Struct({ * A thread that started threads (docs/design/fleet.md, Part 3f, (g)): its * children here that can come along, each with why it can't when it can't * (it then stays here as its own thread), and the threads its agent - * started on other computers, which stay there. On a child: its parent. + * started on other computers, which stay there. On a child: its parent, + * and how many threads moving the whole family moves (`familySize`: the + * parent and its children here; absent from an older server). */ family: Schema.optional( Schema.Struct({ - parent: Schema.optional(Schema.Struct({ threadId: ThreadId, title: TrimmedNonEmptyString })), + parent: Schema.optional( + Schema.Struct({ + threadId: ThreadId, + title: TrimmedNonEmptyString, + familySize: Schema.optional(PositiveInt), + }), + ), children: Schema.Array( Schema.Struct({ threadId: ThreadId, diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index c636c2ca6..e0d0e49f9 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -24,6 +24,7 @@ import { ProjectCreateCommand, ThreadMovePhase, ThreadPendingMove, + ThreadRemoteChildUpdatedPayload, ThreadTurnStartCommand, ThreadCreatedPayload, ThreadTurnDiff, @@ -40,8 +41,8 @@ import { ThreadMoveRequestId, ThreadParticipantId, } from "./baseSchemas.ts"; -import { ThreadMoveQueueInput } from "./moves.ts"; -import { PeerDescriptor, PeerMoveGitManifest, PeerMovePart } from "./peerRpc.ts"; +import { ThreadMovePreview, ThreadMoveQueueInput } from "./moves.ts"; +import { PeerDescriptor, PeerMoveGitManifest, PeerMovePart, PeerMoveState } from "./peerRpc.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput); @@ -913,3 +914,125 @@ it("an app or computer from before families moved still reads a family's move", }); assert.strictEqual(Schema.decodeUnknownSync(BasePeerDescriptor)(descriptor).moves, true); }); + +// What an app or a computer from before threads crossed the link they came +// over (docs/design/fleet.md, Part 3f, (h)) decodes of that move: the fields +// it knew, no more. A child alone and a thread going home are never sent to +// such a computer (`moveLinkLineage`), but it still reads descriptors, move +// answers, previews and a parent's record of its children. +const BasePeerMoveState = Schema.Struct({ + status: Schema.Literals([ + "awaiting_approval", + "receiving", + "staged_awaiting_approval", + "importing", + "committed", + "aborted", + ]), + bytesReceived: Schema.Number, + threadId: Schema.optional(Schema.String), +}); +const BaseThreadRemoteChildUpdatedPayload = Schema.Struct({ + threadId: Schema.String, + child: Schema.Struct({ environmentId: Schema.String, threadId: Schema.String }), + updatedAt: Schema.String, +}); +const BaseThreadMovePreview = Schema.Struct({ + family: Schema.optional( + Schema.Struct({ + parent: Schema.optional(Schema.Struct({ threadId: Schema.String, title: Schema.String })), + children: Schema.Array(Schema.Struct({ threadId: Schema.String })), + remoteChildren: Schema.Array(Schema.Struct({ label: Schema.String })), + }), + ), + targets: Schema.Array(Schema.Struct({ environmentId: Schema.String, label: Schema.String })), +}); + +it("an app or computer from before threads crossed their link still reads that move", () => { + const environmentId = EnvironmentId.make("environment-mac"); + const state = Schema.encodeSync(PeerMoveState)({ + status: "committed", + bytesReceived: 10, + threadId: ThreadId.make("there"), + keptParent: true, + }); + assert.strictEqual(Schema.decodeUnknownSync(BasePeerMoveState)(state).threadId, "there"); + const manifest = Schema.encodeSync(PeerMoveGitManifest)({ + totalBytes: 0, + sha256: "x", + parts: [], + source: { + environmentId: EnvironmentId.make("environment-windows"), + environmentLabel: "Windows PC", + threadId: ThreadId.make("c"), + }, + project: { canonicalKey: "example.com/repo", title: "Threadlines" }, + git: { headSha: "h", branch: "main", baseSha: null }, + thread: { + title: "Fix tests", + runtimeMode: "auto-accept-edits", + interactionMode: "default", + messages: [], + activities: [], + }, + agent: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + summary: { messageCount: 0, trackedFiles: 0, untrackedFiles: 0, unpushedCommits: 0 }, + linkLineage: { remoteParent: { threadId: ThreadId.make("p"), title: "Ship it" } }, + }); + assert.strictEqual(Schema.decodeUnknownSync(BasePeerMoveGitManifest)(manifest).sha256, "x"); + const removed = Schema.encodeSync(ThreadRemoteChildUpdatedPayload)({ + threadId: ThreadId.make("p"), + child: { + environmentId, + label: "Mac mini", + threadId: ThreadId.make("there"), + handle: "Agent", + title: "Fix tests", + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: "2026-11-17T14:00:00.000Z", + }, + removed: true, + updatedAt: "2026-11-17T14:00:00.000Z", + }); + assert.strictEqual( + Schema.decodeUnknownSync(BaseThreadRemoteChildUpdatedPayload)(removed).child.threadId, + "there", + ); + const preview = Schema.encodeSync(ThreadMovePreview)({ + family: { + parent: { threadId: ThreadId.make("p"), title: "Ship it", familySize: 3 }, + children: [], + remoteChildren: [], + }, + targets: [ + { + environmentId, + label: "Mac mini", + agents: [], + aloneRefusal: + "Update Threadlines on Mac mini to move it without the thread that started it.", + }, + ], + }); + assert.strictEqual( + Schema.decodeUnknownSync(BaseThreadMovePreview)(preview).family?.parent?.title, + "Ship it", + ); + const descriptor = Schema.encodeSync(PeerDescriptor)({ + environmentId, + label: "Mac mini", + platform: "darwin", + serverVersion: "1.0.0", + directRoutes: [], + access: "allowed", + maxRuntimeMode: "full-access", + agents: [], + defaultAgent: null, + projects: [], + moves: true, + moveFamilies: true, + moveLinkLineage: true, + }); + assert.strictEqual(Schema.decodeUnknownSync(BasePeerDescriptor)(descriptor).moves, true); +}); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index dbfe848c5..626b361ea 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -884,6 +884,12 @@ export const ThreadMoveTakes = Schema.Struct({ * stay here as their own threads. */ families: Schema.optional(Schema.Literal(true)), + /** + * A thread moving across the link its work came over (docs/design/fleet.md, + * Part 3f, (h)): a child without its parent, which stays its parent's child + * there, and a thread another computer's agent started, going back home. + */ + linkLineage: Schema.optional(Schema.Literal(true)), }); export type ThreadMoveTakes = typeof ThreadMoveTakes.Type; @@ -5445,6 +5451,12 @@ const ThreadMoveCompleteCommand = Schema.Struct({ threadId: ThreadId, transferId: ThreadMoveId, movedThreadId: ThreadId, + /** + * A child that moved without its parent landed there as its parent's child + * across the link (PeerMoveState.keptParent): the parent here keeps it as a + * child on that computer. Absent: it is a thread of its own there. + */ + keptParent: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); @@ -5597,6 +5609,22 @@ const ThreadImportCommand = Schema.Struct({ * family, never from a path the other computer named. */ worktreeOrigin: Schema.optional(ThreadWorktreeOrigin), + /** + * A child that moved without its parent (docs/design/fleet.md, Part 3f, + * (h)): it lands as that parent's child across the link, fenced for good, + * as a thread that link started here is. Built by the link's move handler + * from the link the move came over (never from the manifest), only for a + * link whose computer is pinned, and for the computer it came from. + */ + remoteOrigin: Schema.optional(ThreadRemoteOrigin), + /** + * A thread this computer's agent started on another computer, coming home + * (docs/design/fleet.md, Part 3f, (h)): it lands as `parentThreadId`'s + * child here, and that parent stops keeping it as a child on the computer + * it came from. Only when the parent here already holds exactly this + * thread there (`movedFrom`) as its child. + */ + adopt: Schema.optional(Schema.Struct({ parentThreadId: ThreadId })), /** * What the "Moved here" line says came along (`brought`) and didn't * (`left`), in plain words, and the message Threadlines writes for the @@ -6174,6 +6202,12 @@ export const ThreadRemoteCancelQueuedPayload = Schema.Struct({ export const ThreadRemoteChildUpdatedPayload = Schema.Struct({ threadId: ThreadId, child: RemoteChildThread, + /** + * The child left that computer for this one and is a child here again + * (docs/design/fleet.md, Part 3f, (h), "Moving back home"): its record goes. + * Absent: the record is written as `child` says. + */ + removed: Schema.optional(Schema.Literal(true)), updatedAt: IsoDateTime, }); diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts index 3f9b93038..79b20bc66 100644 --- a/packages/contracts/src/peerRpc.ts +++ b/packages/contracts/src/peerRpc.ts @@ -276,6 +276,16 @@ export const PeerDescriptor = Schema.Struct({ * family is never sent to it. */ moveFamilies: Schema.optional(Schema.Boolean), + /** + * Takes a thread across the link it was started over (docs/design/fleet.md, + * Part 3f, (h)): a child moving without its parent stays that parent's + * child here (PeerMoveManifest's `linkLineage.remoteParent`), and a thread + * this computer's agent started there comes back home as its child again + * (`linkLineage.home`); `keptParent` on the committed answer. Absent: an + * older server, which would land either as a plain thread, so neither is + * ever sent to it. + */ + moveLinkLineage: Schema.optional(Schema.Boolean), /** * Says how the caller's threads here are filed (`filing` on `thread` watch * events) and takes `peer.thread.wrap`. Absent: an older server that can't. @@ -728,6 +738,32 @@ export const PeerMoveFamily = Schema.Struct({ }); export type PeerMoveFamily = typeof PeerMoveFamily.Type; +/** + * A thread moving across the link its work came over (docs/design/fleet.md, + * Part 3f, (h)), with the sending computer's ids. Only to a computer that + * says `moveLinkLineage`, and never with `family`. Exactly one of: + * + * - `remoteParent`: a child moving without its parent, which stays on the + * sending computer. The receiving computer may land it as that parent's + * child across the link: it writes the link and the computer itself + * (`remoteOrigin`), from the link the move came over and only when that + * link's computer is pinned; the sender names only its own thread. + * - `home`: a thread an agent on the receiving computer started on the + * sending one, coming back. The receiving computer lands it under + * `parentThreadId` only when its own records already hold this very + * thread, on the sending computer, as that parent's child. + * + * Neither is ever trusted beyond that: anything else lands as a thread of + * its own. + */ +export const PeerMoveLinkLineage = Schema.Struct({ + remoteParent: Schema.optional( + Schema.Struct({ threadId: ThreadId, title: TrimmedNonEmptyString }), + ), + home: Schema.optional(Schema.Struct({ parentThreadId: ThreadId })), +}); +export type PeerMoveLinkLineage = typeof PeerMoveLinkLineage.Type; + /** * A General Chats thread moving here (docs/design/fleet.md, Part 3e, (d)): * no project to match and no git; its folder's files are the `file` parts, @@ -751,6 +787,8 @@ export const PeerMoveScratchManifest = Schema.Struct({ sessionOmitted: Schema.optional(Schema.Literal("too_large")), /** It moves with its family: see PeerMoveFamily. */ family: Schema.optional(PeerMoveFamily), + /** It moves across the link its work came over: see PeerMoveLinkLineage. */ + linkLineage: Schema.optional(PeerMoveLinkLineage), }); export type PeerMoveScratchManifest = typeof PeerMoveScratchManifest.Type; @@ -800,6 +838,8 @@ export const PeerMoveGitManifest = Schema.Struct({ * has no bundle, diff or files, and `git` says where that folder stands. */ family: Schema.optional(PeerMoveFamily), + /** It moves across the link its work came over: see PeerMoveLinkLineage. */ + linkLineage: Schema.optional(PeerMoveLinkLineage), }); export type PeerMoveGitManifest = typeof PeerMoveGitManifest.Type; @@ -877,6 +917,13 @@ export const PeerMoveState = Schema.Struct({ * another reason, or an older server. */ abortCode: Schema.optional(PeerMoveAbortCode), + /** + * `committed`: it landed as the child of the thread that started it on the + * calling computer, across this link (PeerMoveLinkLineage `remoteParent`), + * so that thread can still reach it here. Absent: it is a thread of its + * own here, or an older server. + */ + keptParent: Schema.optional(Schema.Literal(true)), }); export type PeerMoveState = typeof PeerMoveState.Type; diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 3a2142e93..0084ab71d 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -696,15 +696,25 @@ export const childRequestStateOn = { ? state : { ...state, remoteCancels: [...cancels, cancel] }; }, - /** A child on a linked computer, new or changed; kept after its requests settle. */ + /** + * A child on a linked computer, new or changed; kept after its requests + * settle. `removed`: it came home and is a child here again, so its record goes. + */ remoteChildUpdated: ( state: OrchestrationChildRequestState, child: RemoteChildThread, + removed?: boolean, ): OrchestrationChildRequestState => { const children = state.remoteChildren ?? []; const index = children.findIndex( (entry) => entry.environmentId === child.environmentId && entry.threadId === child.threadId, ); + if (removed === true) { + if (index < 0) return state; + const rest = children.filter((_, at) => at !== index); + const { remoteChildren: _gone, ...without } = state; + return rest.length > 0 ? { ...state, remoteChildren: rest } : without; + } if (index >= 0 && sameRemoteChild(children[index]!, child)) { return state; }