From e97ce47541855f1aea691b7610af5fe0b6f201dd Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:10:21 -0500 Subject: [PATCH 1/3] feat(server): a parent moving to its child's computer takes the child back A thread's agent on computer A could start a child on computer B over a link. If that parent later moved to B, the child stayed stranded: fenced for good, pointing at A's read-only copy, its reports to A retried forever, and nobody could direct it. Now the moving parent takes such threads back as its own children on B. A sends the list it holds (PeerMoveManifest.startedThere, only to a computer that says moveAdoptsChildren). B adopts only threads its own records also name as started over that link by that thread, and only when the decider's checks pass (same link, origin thread, pinned computer, project, not archived or moving, no children, within the parent's access). Before the import, B's link releases each one: open requests end, queued messages are taken back, the request's own running turn stops, and the ledger owes the link nothing more. The adopted child clears remoteOrigin, carries adoptedFromLink, and stays fenced until the user writes in it. The committed answer names the adopted threads, and A's read-only copy drops their records. LinkRequests now checks the thread is still the link's before any cancel clean-up, ack, send, read, stop or wrap, so a late cancel can't stop the user's new turn. --- apps/server/src/guide/topics.ts | 2 +- apps/server/src/links/LinkMoves.test.ts | 128 +++++++- apps/server/src/links/LinkMoves.ts | 169 +++++++--- .../server/src/links/LinkRequestRepository.ts | 31 ++ apps/server/src/links/LinkRequests.test.ts | 176 +++++++++++ apps/server/src/links/LinkRequests.ts | 119 ++++++- .../src/links/RemoteChildReactor.test.ts | 40 +++ apps/server/src/links/RemoteChildReactor.ts | 12 +- apps/server/src/links/peerRoute.ts | 1 + apps/server/src/moves/ThreadMoves.test.ts | 35 ++- apps/server/src/moves/ThreadMoves.ts | 23 +- apps/server/src/moves/familyMove.ts | 22 +- apps/server/src/moves/moveExport.ts | 13 + .../Layers/ProjectionPipeline.ts | 20 +- .../Layers/ProjectionSnapshotQuery.ts | 10 + .../src/orchestration/childThreadDecisions.ts | 63 +++- .../orchestration/decider.threadMoves.test.ts | 295 +++++++++++++++++- apps/server/src/orchestration/linkFence.ts | 61 ++-- apps/server/src/orchestration/projector.ts | 21 +- .../src/orchestration/threadMoveDecisions.ts | 246 ++++++++++++++- .../persistence/Layers/ProjectionThreads.ts | 30 ++ apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/120_ThreadAdoptedFromLink.ts | 16 + .../persistence/Services/ProjectionThreads.ts | 16 + .../components/ThreadMoveDialogContent.tsx | 10 +- apps/web/src/store.ts | 19 +- apps/web/src/threadMove.test.ts | 30 ++ apps/web/src/threadMove.ts | 45 ++- docs/design/fleet.md | 19 +- packages/contracts/src/moves.ts | 13 +- packages/contracts/src/orchestration.ts | 77 ++++- packages/contracts/src/peerRpc.ts | 37 +++ packages/shared/src/threadMoveProjection.ts | 13 + 33 files changed, 1676 insertions(+), 138 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/120_ThreadAdoptedFromLink.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 821d2291e..db35768c5 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, and the thread can move only back to the computer it came from. If the link it came over can't confirm which computer sent it, it can't move at all until then. 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. Moved to the computer one of them is on, its "Moved here" line names that thread, which stays separate. 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. With its whole family, each thread moves with the agent the other computer suggests for it. 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.`, +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. If the link it came over can't confirm which computer sent it, it can't move at all until then. 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. Moved to the computer one of them is on, when that computer runs a current Threadlines, that thread is its thread again there, nested under it, and its "Moved here" line says so; one that started threads of its own, is archived or moving, or has more access than the moved thread gets there stays separate, and the line says why. The thread taken back has no other threads, rooms or schedules, and can move only back to the computer that started it, until you send it a message there; a message in its parent doesn't count. 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. With its whole family, each thread moves with the agent the other computer suggests for it. 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 51cb523c1..1fe7e512c 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -184,6 +184,12 @@ interface CarryRecord { readonly linkLabel?: string; /** Threads already here, as their rows read. */ readonly threadsHere?: ReadonlyArray<{ readonly threadId: ThreadId } & Record>; + /** + * Threads this link gave up (LinkRequests.releaseThread), each with how + * many commands were dispatched by then, and the ones closed for it after. + */ + readonly released?: Array<{ readonly threadId: ThreadId; readonly dispatchedBefore: number }>; + readonly closed?: Array; } /** The services LinkMoves leans on, with this computer's git real and the rest faked. */ @@ -229,6 +235,12 @@ function testLayer( title: "Threadlines", workspaceRoot: repos.b, } as never), + releaseThread: (_deviceId, threadId) => + Effect.sync( + () => void carry.released?.push({ threadId, dispatchedBefore: dispatched.length }), + ), + closeThread: (_deviceId, threadId) => + Effect.sync(() => void carry.closed?.push(threadId)), // An instance this computer doesn't have ("gone") is refused. resolveAgentFor: (input) => Effect.succeed( @@ -279,6 +291,15 @@ function testLayer( // A thread here once its import was dispatched (a family's child reads // its parent), or one that was here already. Layer.mock(ProjectionThreadRepository)({ + // As the decider would write them: every thread the import asked for. + listAdoptedChildIds: ({ parentThreadId }) => + Effect.sync(() => + dispatched.flatMap((command) => + command.type === "thread.import" && command.threadId === parentThreadId + ? (command.adoptsChildren?.children ?? []).map((child) => child.threadId) + : [], + ), + ), listIdsByRemoteLink: ({ linkDeviceId }) => Effect.succeed( (carry.threadsHere ?? []).flatMap((row) => @@ -372,7 +393,10 @@ const pack = ( repos: ReturnType, nativeSession?: NativeSessionExport | null, state?: PeerMoveThreadState, - room?: Pick & { + room?: Pick< + MoveExportInput, + "room" | "outsideWork" | "family" | "linkLineage" | "startedThere" + > & { /** What the move says the computer it leaves calls itself. */ readonly sourceEnvironmentId?: EnvironmentId | undefined; readonly sourceLabel?: string; @@ -394,6 +418,7 @@ const pack = ( dir, family: room?.family, linkLineage: room?.linkLineage, + startedThere: room?.startedThere, attachmentsDir: path.join(repos.root, "attachments"), thread: room?.thread ?? movingThread(), room: room?.room, @@ -2266,6 +2291,107 @@ describe("a thread moving across its link (Part 3f, (h))", () => { }); }); + describe("a parent taking back the threads it started here (Part 3f, (g))", () => { + /** A thread the link started here for the moving thread (`thread-a` there). */ + const startedHere = (threadId: string, title: string) => ({ + threadId: ThreadId.make(threadId), + title, + deletedAt: null, + archivedAt: null, + remoteOrigin: { + linkDeviceId: "device-windows", + environmentId: WINDOWS, + environmentPinned: true, + environmentLabel: "Windows PC", + threadId: "thread-a", + threadTitle: "Ship it", + }, + }); + const wrapped = { state: "done", at: "2026-11-17T09:00:00.000Z" } as const; + const startedThere = [ + { threadId: ThreadId.make("thread-both"), override: wrapped }, + // On its list there, but not a thread this link started here for it. + { threadId: ThreadId.make("thread-not-here") }, + ]; + const arriving = ( + repos: ReturnType, + dispatched: OrchestrationCommand[], + carry: Pick, + linkLineage?: MoveExportInput["linkLineage"], + ) => + Effect.gen(function* () { + const packed = yield* pack(repos, null, undefined, { startedThere, linkLineage }); + const state = yield* deliver(packed.manifest, packed.payload); + // Asked again (a restart, a lost answer): read from the threads, the same. + const again = yield* (yield* LinkMoves).status(link("allowed"), { transferId: TRANSFER }); + return { state, again }; + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + linkLabel: "Windows PC", + pinnedEnvironmentId: WINDOWS, + threadsHere: [ + startedHere("thread-both", "Fix tests"), + startedHere("thread-only-here", "Only here"), + ], + ...carry, + }), + ), + ); + + it.live("only those both its list and this computer's records name, released first", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + const released: NonNullable = []; + const closed: ThreadId[] = []; + return Effect.gen(function* () { + const { state, again } = yield* arriving(repos, dispatched, { released, closed }); + assert.equal(state.status, "committed"); + const imported = importOf(dispatched); + assert.deepEqual(imported.adoptsChildren, { + linkDeviceId: "device-windows", + children: [{ threadId: ThreadId.make("thread-both"), override: wrapped }], + }); + // Here but not on its list: it stays apart, with today's words. + assert.deepEqual( + (imported.arrival?.left ?? []).filter((sentence) => sentence.includes("this computer")), + [ + "Its thread 'Only here' is already on this computer. It stays separate, so this thread can't reach it.", + ], + ); + // The link let go of it before the import, and owes it nothing once it landed. + assert.deepEqual( + released.map((entry) => entry.threadId), + ["thread-both"], + ); + assert.isAtMost(released[0]!.dispatchedBefore, dispatched.indexOf(imported)); + assert.include(closed, ThreadId.make("thread-both")); + assert.deepEqual(state.adopted, [ThreadId.make("thread-both")]); + assert.deepEqual(again.adopted, [ThreadId.make("thread-both")]); + }); + }); + + it.live("a thread landing under a parent takes none back", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + const released: NonNullable = []; + return Effect.gen(function* () { + const { state } = yield* arriving( + repos, + dispatched, + { released, closed: [] }, + { remoteParent: { threadId: ThreadId.make("thread-parent-on-windows"), title: "Ship" } }, + ); + assert.equal(state.status, "committed"); + assert.isUndefined(importOf(dispatched).adoptsChildren); + assert.deepEqual(released, []); + assert.isUndefined(state.adopted); + }); + }); + }); + it("refuses a manifest naming both a parent and a home, itself, or a family too", () => { const base = { totalBytes: 0, diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 22d83825e..d90c4f2f8 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -62,6 +62,7 @@ import { type RuntimeMode, PEER_MOVE_CHUNK_MAX_BYTES, PEER_MOVE_FAMILY_MAX_STAYED, + PEER_MOVE_MAX_STARTED_THERE, PEER_MOVE_ROOM_MAX_PARTICIPANTS, PEER_MOVE_STATE_MAX_BYTES, PEER_MOVE_STATE_MAX_CHECK_BACKS, @@ -365,6 +366,9 @@ export function moveManifestRefusal(manifest: PeerMoveManifest): string | null { if (ownSessionParts > 0 !== (manifest.session !== undefined)) { return "its session doesn't match its files"; } + if ((manifest.startedThere ?? []).length > PEER_MOVE_MAX_STARTED_THERE) { + return "it names too many threads it started here"; + } return ( moveRoomRefusal(manifest) ?? moveFamilyRefusal(manifest) ?? @@ -1398,6 +1402,7 @@ const make = Effect.gen(function* () { ); } } + yield* closeAdopted(row); return yield* moves.settle({ linkDeviceId: row.linkDeviceId, transferId: row.transferId, @@ -2433,14 +2438,14 @@ const make = Effect.gen(function* () { }); /** - * The titles of the threads its agent started on this computer while it - * was on the one it came from (docs/design/fleet.md, Part 3f, (g), "Also - * when the child's computer is the target"). They stay that computer's - * children, apart from the thread that arrives, which can't reach them. - * Read from this computer's own records alone: threads started over this - * very link by the thread the move came from, still here (not archived, - * deleted or moved away). A failed read names none rather than failing the - * move. + * The threads its agent started on this computer while it was on the one + * it came from (docs/design/fleet.md, Part 3f, (g), "Also when the child's + * computer is the target"). Read from this computer's own records alone: + * threads started over this very link by the thread the move came from, + * still here (not archived, deleted or moved away). Those the manifest + * also names (`startedThere`) may become the arriving thread's children; + * the rest stay apart, and it can't reach them. A failed read names none + * rather than failing the move. */ const threadsStartedHere = (row: LinkMoveRow) => Effect.gen(function* () { @@ -2448,18 +2453,43 @@ const make = Effect.gen(function* () { const found = yield* Effect.forEach(ids, (threadId) => threadRows.getById({ threadId }), { concurrency: 8, }); - return found.flatMap((entry): string[] => { - const thread = Option.getOrUndefined(entry); - return thread !== undefined && - thread.deletedAt === null && - thread.archivedAt === null && - thread.move?.movedAway === undefined && - thread.remoteOrigin?.linkDeviceId === row.linkDeviceId && - thread.remoteOrigin.threadId === row.manifest.source.threadId - ? [thread.title] - : []; - }); - }).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + return found.flatMap( + (entry): Array<{ readonly threadId: ThreadId; readonly title: string }> => { + const thread = Option.getOrUndefined(entry); + return thread !== undefined && + thread.deletedAt === null && + thread.archivedAt === null && + thread.move?.movedAway === undefined && + thread.remoteOrigin?.linkDeviceId === row.linkDeviceId && + thread.remoteOrigin.threadId === row.manifest.source.threadId + ? [{ threadId: thread.threadId, title: thread.title }] + : []; + }, + ); + }).pipe( + Effect.orElseSucceed( + (): ReadonlyArray<{ readonly threadId: ThreadId; readonly title: string }> => [], + ), + ); + + /** + * After the thread landed: the threads it took back as its children here + * owe the link nothing more (LinkRequests.closeThread), whatever arrived + * between their release and the import. Read from the projection, so a + * restart in between closes them too. + */ + const closeAdopted = (row: LinkMoveRow) => + Effect.gen(function* () { + const adopted = yield* threadRows.listAdoptedChildIds({ parentThreadId: row.threadId }); + for (const threadId of adopted) yield* requests.closeThread(row.linkDeviceId, threadId); + }).pipe( + Effect.catch((error) => + Effect.logWarning("a moved thread's adopted threads couldn't be closed for their link", { + threadId: row.threadId, + detail: String(error), + }), + ), + ); /** The "Moved here" words for threadsStartedHere, or null for none. */ const startedHereWords = (titles: ReadonlyArray) => { @@ -2664,7 +2694,13 @@ const make = Effect.gen(function* () { const lineage = family === null ? null : yield* family.lineage(land.project.id); const startedHere = yield* threadsStartedHere(row); const familyLeft = - family === null ? [] : family.left(fromLabel, lineage?.left ?? null, new Set(startedHere)); + family === null + ? [] + : family.left( + fromLabel, + lineage?.left ?? null, + new Set(startedHere.map((entry) => entry.title)), + ); // Across the link its work came over (Part 3f, (h)): from this link alone. const across = yield* linkLanding( row, @@ -2673,7 +2709,26 @@ const make = Effect.gen(function* () { fromLabel, ); if (across.left !== undefined) familyLeft.push(across.left); - const startedHereLine = startedHereWords(startedHere); + // The threads it started here that may be its children again (Part 3f, + // (g)): named by both the manifest and this computer's own records, + // and only for a thread that lands on its own here. The decider checks + // each again and words the outcome; the others stay apart, named here. + const askedBack = new Map( + (row.manifest.startedThere ?? []).map((entry) => [entry.threadId as string, entry]), + ); + const topLevel = + lineage?.lineage === undefined && + across.remoteOrigin === undefined && + across.adopt === undefined; + const adoptable = topLevel + ? startedHere.filter((entry) => askedBack.has(entry.threadId)) + : []; + const adoptableIds = new Set(adoptable.map((entry) => entry.threadId)); + const startedHereLine = startedHereWords( + startedHere + .filter((entry) => !adoptableIds.has(entry.threadId)) + .map((entry) => entry.title), + ); if (startedHereLine !== null) familyLeft.push(startedHereLine); // The "Moved here" line's room words first, then its family's, then // what the thread had going. @@ -2694,6 +2749,13 @@ const make = Effect.gen(function* () { if (yield* messageIdsTaken(row.threadId, [...roomMessages, ...notSent])) { return yield* stop(`${ownLabel()} already has one of its messages in another thread.`); } + // While the link still holds them: what it asked of them ends here, + // so nothing it asked can act on them once they are this thread's. + // Again on a retry (it is safe to); should the import then fail, they + // stay the link's, with those requests ended. + for (const entry of adoptable) { + yield* requests.releaseThread(row.linkDeviceId, entry.threadId); + } const dispatched = yield* engine .dispatch({ type: "thread.import", @@ -2731,6 +2793,21 @@ const make = Effect.gen(function* () { ...(lineage?.lineage !== undefined ? { lineage: lineage.lineage } : {}), ...(across.remoteOrigin !== undefined ? { remoteOrigin: across.remoteOrigin } : {}), ...(across.adopt !== undefined ? { adopt: across.adopt } : {}), + // The link is this transfer's own, never one the manifest names. + ...(adoptable.length > 0 + ? { + adoptsChildren: { + linkDeviceId: row.linkDeviceId, + children: adoptable.map((entry) => { + const override = askedBack.get(entry.threadId)?.override; + return { + threadId: entry.threadId, + ...(override !== undefined ? { override } : {}), + }; + }), + }, + } + : {}), ...(family?.worktreeOrigin !== undefined ? { worktreeOrigin: family.worktreeOrigin } : {}), @@ -3555,30 +3632,36 @@ const make = Effect.gen(function* () { /** * 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. + * (h)), and which threads it started here became its children (`adopted`, + * Part 3f, (g)): read from the threads themselves, which only this + * computer wrote, so a retried call (after a restart too) 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.`)), - ), - ); + const withLanding = (link: PeerLink) => (answer: Effect.Effect) => + Effect.flatMap(answer, (state) => { + const threadId = state.threadId; + if (state.status !== "committed" || threadId === undefined) return Effect.succeed(state); + return Effect.gen(function* () { + const row = yield* threadRows.getById({ threadId }); + const adopted = yield* threadRows.listAdoptedChildIds({ parentThreadId: threadId }); + return { + ...state, + ...(Option.isSome(row) && row.value.remoteOrigin?.linkDeviceId === link.deviceId + ? { keptParent: true as const } + : {}), + ...(adopted.length > 0 ? { adopted } : {}), + }; + }).pipe( + // 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: (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)), + prepare: (link, input) => prepare(link, input).pipe(withLanding(link)), + chunk: (link, input) => chunk(link, input).pipe(withLanding(link)), + finish: (link, input) => finish(link, input).pipe(withLanding(link)), + status: (link, input) => status(link, input).pipe(withLanding(link)), + abort: (link, input) => abort(link, input).pipe(withLanding(link)), respond, respondMany, pending, diff --git a/apps/server/src/links/LinkRequestRepository.ts b/apps/server/src/links/LinkRequestRepository.ts index a76850586..e3abb77c9 100644 --- a/apps/server/src/links/LinkRequestRepository.ts +++ b/apps/server/src/links/LinkRequestRepository.ts @@ -192,6 +192,18 @@ export interface LinkRequestRepositoryShape { readonly requestId: ChildRequestId; readonly cleanup: LinkRequestCleanup; }) => Effect.Effect; + /** + * A thread a link started stops being that link's (it became a child here + * of the thread that asked, docs/design/fleet.md, Part 3f, (g)): every + * report about it counts as delivered, so no watch offers one again, and + * nothing a cancel or an unlink still owes it is left to do. Call once its + * open requests ended; safe to call again. + */ + readonly closeForThread: (input: { + readonly linkDeviceId: string; + readonly threadId: ThreadId; + readonly now: string; + }) => Effect.Effect; /** The asking computer recorded the report. */ readonly markDelivered: (input: { readonly linkDeviceId: string; @@ -475,6 +487,24 @@ const make = Effect.gen(function* () { AND cleanup = ${input.cleanup} `.pipe(Effect.asVoid, wrap("finishCleanup")); + const closeForThread: LinkRequestRepositoryShape["closeForThread"] = (input) => + Effect.gen(function* () { + yield* sql` + UPDATE link_requests SET delivered_at = ${input.now} + WHERE link_device_id = ${input.linkDeviceId} AND thread_id = ${input.threadId} + AND report_id IS NOT NULL AND delivered_at IS NULL + `; + yield* sql` + UPDATE link_requests SET cleanup = NULL + WHERE link_device_id = ${input.linkDeviceId} AND thread_id = ${input.threadId} + AND cleanup IS NOT NULL + `; + yield* sql` + DELETE FROM link_thread_stops_owed + WHERE link_device_id = ${input.linkDeviceId} AND thread_id = ${input.threadId} + `; + }).pipe(sql.withTransaction, wrap("closeForThread")); + const markDelivered: LinkRequestRepositoryShape["markDelivered"] = (input) => sql` UPDATE link_requests SET delivered_at = ${input.now} @@ -575,6 +605,7 @@ const make = Effect.gen(function* () { cancel, listCleanup, finishCleanup, + closeForThread, markDelivered, prune, }); diff --git a/apps/server/src/links/LinkRequests.test.ts b/apps/server/src/links/LinkRequests.test.ts index dfe27876e..f8738e22b 100644 --- a/apps/server/src/links/LinkRequests.test.ts +++ b/apps/server/src/links/LinkRequests.test.ts @@ -340,6 +340,73 @@ const stopRequestedFor = (events: ReadonlyArray, threadId: T event.type === "thread.session-stop-requested" && event.payload.threadId === threadId, ); +const stopsFor = (events: ReadonlyArray, threadId: ThreadId) => + events.filter( + (event) => + event.type === "thread.session-stop-requested" && event.payload.threadId === threadId, + ).length; + +/** + * The thread that asked (PARENT on Windows PC) moves here and takes the + * link's thread back as its child (docs/design/fleet.md, Part 3f, (g)): + * released by the link first, then imported, as LinkMoves does it. + */ +const takenBack = ( + computer: Computer, + service: Effect.Success>, + threadId: ThreadId, +) => + Effect.gen(function* () { + yield* service.releaseThread(DEVICE, threadId); + yield* computer.engine.dispatch({ + type: "thread.import", + commandId: CommandId.make("import-parent"), + threadId: ThreadId.make("parent-arrived"), + projectId: PROJECT, + title: "Ship the release", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-astra" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + movedFrom: { + environmentId: WINDOWS, + environmentPinned: true, + label: "Windows PC", + threadId: PARENT, + movedAt: AT, + }, + messages: [], + activities: [], + adoptsChildren: { linkDeviceId: DEVICE, children: [{ threadId }] }, + createdAt: AT, + }); + const child = yield* computer.thread(threadId); + assert.equal(child?.parentThreadId, "parent-arrived"); + assert.isNull(child?.remoteOrigin ?? null); + }); + +/** The user here starts a turn in the thread, and its agent is at work on it. */ +const userTurnRunning = (computer: Computer, threadId: ThreadId) => + Effect.gen(function* () { + yield* computer.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("user-turn-running"), + threadId, + session: { + threadId, + status: "running", + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + runtimeMode: "auto", + activeTurnId: TurnId.make("user-turn"), + lastError: null, + updatedAt: AT, + }, + createdAt: AT, + }); + }); + it.layer(NodeServices.layer)("LinkRequests", (it) => { it.effect("records a start once: a retry gets the same thread and starts nothing more", () => Effect.gen(function* () { @@ -1492,6 +1559,115 @@ it.layer(NodeServices.layer)("LinkRequests", (it) => { }), ); + it.effect( + "once its asker took the thread back here, a late cancel stops nothing, after a restart too", + () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { service, threadId } = yield* startedChild(computer, "request-1"); + yield* takenBack(computer, service, threadId); + assert.equal((yield* computer.request("request-1")).status, "cancelled"); + yield* userTurnRunning(computer, threadId); + const before = stopsFor(yield* computer.events, threadId); + + // The stop-now cancel the asker owed from before it moved arrives late. + const late = yield* service.cancel(link(), ChildRequestId.make("request-1"), { + stopThread: true, + }); + assert.equal(late.status, "cancelled"); + assert.equal(stopsFor(yield* computer.events, threadId), before); + assert.isNull((yield* computer.request("request-1")).cleanup); + + // The same cancel recorded just before the process died, its clean-up + // owed: the restart finishes it without touching the thread. + yield* computer.ledger.cancel({ + linkDeviceId: DEVICE, + requestId: ChildRequestId.make("request-1"), + text: "Stopped.", + stopThread: true, + now: AT, + }); + assert.equal((yield* computer.request("request-1")).cleanup, "stop"); + const restarted = yield* computer.boot(); + yield* restarted.startReactor(); + assert.isNull((yield* computer.request("request-1")).cleanup); + assert.equal(stopsFor(yield* computer.events, threadId), before); + }), + ); + + it.effect("a thread its asker took back answers the link as not its own", () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { service, threadId } = yield* startedChild(computer, "request-1"); + yield* takenBack(computer, service, threadId); + const sent = yield* service.send(link(), { + requestId: ChildRequestId.make("send-late"), + threadId, + text: "One more thing.", + }); + assert.equal(sent.status, "refused"); + assert.equal((yield* service.readThread(link(), { threadId, limit: 10 })).outcome, "refused"); + assert.equal((yield* service.stopThread(link(), threadId)).status, "not_yours"); + assert.equal( + (yield* service.wrapThread(link(), { + threadId, + override: { state: "done", at: AT }, + })).status, + "not_yours", + ); + // A late ack of its old answer records nothing on it. + yield* service.ack(link(), { reportId: "request-1:report", delivered: true }); + assert.isNull((yield* computer.thread(threadId))?.handedBackAt ?? null); + }), + ); + + it.effect("once released, a watch offers nothing more about the thread", () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { service, threadId } = yield* startedChild(computer, "request-1"); + // An answer the asker never acked, and the start still running. + yield* service.send(link(), { + requestId: ChildRequestId.make("send-1"), + threadId, + text: "Add the security fixes too.", + }); + const child = (yield* computer.thread(threadId))!; + const answering = TurnId.make("turn-send"); + yield* service.onTurnEnd({ + child: { + ...child, + messages: [ + ...child.messages, + { + id: MessageId.make("answer"), + role: "assistant", + text: "Added the two security fixes.", + turnId: answering, + streaming: false, + createdAt: AT, + updatedAt: AT, + }, + ], + }, + end: { turnId: answering, outcome: "completed" }, + pendingMessageId: linkMessageId(DEVICE, "send-1"), + createdAt: AT, + }); + const offered = yield* replay(service.watch(link(), {})); + assert.isAbove(offered.filter((event) => event.type !== "synced").length, 0); + + yield* service.releaseThread(DEVICE, threadId); + const after = yield* replay(service.watch(link(), {})); + assert.deepEqual( + after.map((event) => event.type), + ["synced"], + ); + }), + ); + it.effect("answers a send with the turn its own message started, not another", () => Effect.gen(function* () { const computer = yield* makeComputer(); diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 62677c44d..a7c6d0a4b 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -248,6 +248,21 @@ export interface LinkRequestsShape { }>, ComputerLinkError >; + /** + * A thread this link started is about to stop being its (docs/design/ + * fleet.md, Part 3f, (g)): the thread that asked moved here over the link + * and takes it back as its own child. Each of the link's requests still + * open for it ends cancelled under its own lock, its message still waiting + * there is taken back, and the thread is stopped only while the turn + * running is that request's; then nothing about it is owed the link any + * more (LinkRequestRepository.closeForThread). Safe to call again. + */ + readonly releaseThread: ( + deviceId: string, + threadId: ThreadId, + ) => Effect.Effect; + /** Every report about the thread counts as delivered: see LinkRequestRepository.closeForThread. */ + readonly closeThread: (deviceId: string, threadId: ThreadId) => Effect.Effect; readonly onTurnEnd: RemoteRequestTurnEndsShape["onTurnEnd"]; /** See RemoteRequestGate. */ readonly messageVerdict: RemoteRequestGateShape["messageVerdict"]; @@ -1036,17 +1051,26 @@ const make = Effect.gen(function* () { // --------------------------------------------------------------------------- /** A thread this link started, or undefined; fails when it can't be read. */ - const linkThread = (link: PeerLink, threadId: ThreadId) => + /** + * The thread, while it is one this link started (`remoteOrigin`) and isn't + * deleted; undefined otherwise. Everything a link's request, cancel, stop + * or ack does to a thread asks this first: a thread its asker took back as + * a child here (Part 3f, (g)) is this computer's own from then on, so a + * late cancel or a replayed clean-up never touches its new work. + */ + const ownedThread = (deviceId: string, threadId: ThreadId) => readThreadOrFail(threadId).pipe( Effect.map((thread) => thread !== undefined && thread.deletedAt === null && - thread.remoteOrigin?.linkDeviceId === link.deviceId + thread.remoteOrigin?.linkDeviceId === deviceId ? thread : undefined, ), ); + const linkThread = (link: PeerLink, threadId: ThreadId) => ownedThread(link.deviceId, threadId); + const sendAnswer = (row: LinkRequestRow): PeerSendResult => row.status === "cancelled" ? { status: "cancelled" } @@ -1069,7 +1093,7 @@ const make = Effect.gen(function* () { const row = found.value; if (row.status !== "received" || row.payload?.kind !== "send") return sendAnswer(row); const input = row.payload.input; - const thread = row.threadId === null ? undefined : yield* readThreadOrFail(row.threadId); + const thread = row.threadId === null ? undefined : yield* ownedThread(deviceId, row.threadId); const origin = thread?.remoteOrigin ?? null; if (thread === undefined || origin === null || row.messageId === null) { const reason = `That thread is gone from ${ownLabel()}.`; @@ -1255,7 +1279,8 @@ const make = Effect.gen(function* () { if (Option.isNone(found) || found.value.cleanup === null) return; const row = found.value; const cleanup = found.value.cleanup; - const thread = row.threadId === null ? undefined : yield* readThreadOrFail(row.threadId); + // Not the link's any more: nothing is done to it, and the clean-up ends. + const thread = row.threadId === null ? undefined : yield* ownedThread(deviceId, row.threadId); const messageId = row.messageId; if ( thread !== undefined && @@ -1275,7 +1300,7 @@ const make = Effect.gen(function* () { ); } if (thread !== undefined && cleanup === "stop") { - const current = yield* readThreadOrFail(thread.id); + const current = yield* ownedThread(deviceId, thread.id); if (current !== undefined) yield* stopIfWorking(deviceId, current); } yield* ledger @@ -1306,6 +1331,73 @@ const make = Effect.gen(function* () { } as const; }); + const releaseThread: LinkRequestsShape["releaseThread"] = (deviceId, threadId) => + Effect.gen(function* () { + const rows = yield* ledger + .listByThread(threadId) + .pipe(Effect.mapError(() => peerError(`${ownLabel()} couldn't read the requests.`))); + for (const listed of rows) { + if (listed.linkDeviceId !== deviceId || isTerminalLinkRequest(listed)) continue; + yield* withRequestLock( + deviceId, + listed.requestId, + )( + Effect.gen(function* () { + const found = yield* readRequest(deviceId, listed.requestId); + if (Option.isNone(found) || isTerminalLinkRequest(found.value)) return; + const row = found.value; + // Ended, not published: the asker's copy of its thread moved away, + // and closeForThread below marks the report delivered. + yield* ledger + .cancel({ + linkDeviceId: deviceId, + requestId: row.requestId, + text: "The thread that asked moved here.", + stopThread: false, + now: yield* nowIso, + }) + .pipe(Effect.mapError(() => peerError(`${ownLabel()} couldn't record the cancel.`))); + const thread = yield* ownedThread(deviceId, threadId); + if (thread === undefined) return; + const messageId = row.messageId; + if ( + messageId !== null && + (thread.queuedFollowUps ?? []).some((queued) => queued.messageId === messageId) + ) { + yield* mustDispatch( + { + type: "thread.follow-up.unqueue", + commandId: linkCommandId(deviceId, row.requestId, "release-unqueue"), + threadId, + messageId, + createdAt: yield* nowIso, + }, + "take back the message of the thread that moved here", + ); + } + // Only the turn this request asked for: any other is this computer's user's. + const current = yield* ownedThread(deviceId, threadId); + if ( + current !== undefined && + row.turnId !== null && + current.latestTurn?.turnId === row.turnId && + isRunning(current) + ) { + yield* stopIfWorking(deviceId, current); + } + }), + ); + } + yield* closeThread(deviceId, threadId); + }); + + const closeThread: LinkRequestsShape["closeThread"] = (deviceId, threadId) => + Effect.gen(function* () { + yield* ledger + .closeForThread({ linkDeviceId: deviceId, threadId, now: yield* nowIso }) + .pipe(Effect.mapError(() => peerError(`${ownLabel()} couldn't record the requests.`))); + }); + const cancel: LinkRequestsShape["cancel"] = (link, requestId, options) => cancelRequest( link.deviceId, @@ -1418,8 +1510,14 @@ const make = Effect.gen(function* () { const row = yield* ledger .getByReport(link.deviceId, input.reportId) .pipe(Effect.mapError(failed)); + // A thread the link no longer has (its asker took it back here) records nothing. + const owned = + Option.isSome(row) && row.value.threadId !== null + ? yield* ownedThread(link.deviceId, row.value.threadId) + : undefined; if ( Option.isSome(row) && + owned !== undefined && row.value.deliveredAt === null && row.value.threadId !== null && row.value.reportTurnId !== null @@ -1680,13 +1778,8 @@ const make = Effect.gen(function* () { const attempt = yield* nowIso; for (const owed of stops.value) { yield* Effect.gen(function* () { - const thread = yield* readThreadOrFail(owed.threadId); - if ( - thread === undefined || - thread.deletedAt !== null || - !isRunning(thread) || - turnKeyOf(thread) !== owed.turnKey - ) { + const thread = yield* ownedThread(owed.linkDeviceId, owed.threadId); + if (thread === undefined || !isRunning(thread) || turnKeyOf(thread) !== owed.turnKey) { yield* ledger.clearThreadStopOwed(owed); yield* Effect.logInfo("link requests saw an unlinked link's thread stop", { threadId: owed.threadId, @@ -2350,6 +2443,8 @@ const make = Effect.gen(function* () { oweDrain, drainDone, drainsOwed, + releaseThread, + closeThread, onTurnEnd, messageVerdict, startReactor, diff --git a/apps/server/src/links/RemoteChildReactor.test.ts b/apps/server/src/links/RemoteChildReactor.test.ts index 87a05653c..d55c8c464 100644 --- a/apps/server/src/links/RemoteChildReactor.test.ts +++ b/apps/server/src/links/RemoteChildReactor.test.ts @@ -718,4 +718,44 @@ it.layer(NodeServices.layer)("RemoteChildReactor", (it) => { ); }), ); + + it.effect( + "a parent that moved away acks a report about its thread there as not delivered, never again offered", + () => + Effect.gen(function* () { + const computer = yield* makeComputer; + yield* computer.askForThread; + yield* computer.recordRemote("running", { status: "accepted", threadId: REMOTE_CHILD }); + // Its copy here is read-only: it moved to Mac mini (and may have taken + // that thread back as its own there, docs/design/fleet.md, Part 3f, (g)). + const movedAway = { + move: { + transferId: "transfer-1", + target: { environmentId: MAC_MINI, label: "Mac mini" }, + agent: MODEL, + phase: "exporting", + cancelRequested: false, + startedAt: AT, + movedAway: { threadId: ThreadId.make("thread-there"), movedAt: AT }, + }, + }; + const asMoved = { + getById: (input: { readonly threadId: ThreadId }) => + computer.threadRows + .getById(input) + .pipe(Effect.map(Option.map((row) => ({ ...row, ...movedAway }) as typeof row))), + }; + yield* computer.boot({ watch: [report({}), { type: "synced" }] }, { threadRows: asMoved }); + yield* eventually( + Effect.sync(() => computer.callsTo("peer.report.ack").length > 0), + "the report is acked", + ); + assert.deepEqual(computer.callsTo("peer.report.ack")[0]?.payload, { + reportId: `${REQUEST}:report`, + delivered: false, + }); + // Nothing was written into the read-only copy. + assert.lengthOf((yield* computer.stored).childRequests?.open ?? [], 1); + }), + ); }); diff --git a/apps/server/src/links/RemoteChildReactor.ts b/apps/server/src/links/RemoteChildReactor.ts index b59777120..917b54521 100644 --- a/apps/server/src/links/RemoteChildReactor.ts +++ b/apps/server/src/links/RemoteChildReactor.ts @@ -595,8 +595,16 @@ const make = Effect.gen(function* () { const found = yield* findRequest(environmentId, event.requestId); // A parent whose move stopped its agent can't take the answer (it // would refuse it, and a refusal reads as settled meanwhile): the - // report stays unacked there and comes again with a later watch. - if (found !== undefined && familyWorkStopped(found.parent)) return; + // report stays unacked there and comes again with a later watch, + // should the move be dropped. Once the parent moved away it never + // takes one: the report is acked as not delivered, so that + // computer stops offering it. + if (found !== undefined && familyWorkStopped(found.parent)) { + if (found.parent.move?.movedAway !== undefined) { + yield* ackReport(environmentId, event.reportId, false); + } + return; + } if (found !== undefined) { const { parent, request } = found; const silent = diff --git a/apps/server/src/links/peerRoute.ts b/apps/server/src/links/peerRoute.ts index 88b8f4244..feb398b8e 100644 --- a/apps/server/src/links/peerRoute.ts +++ b/apps/server/src/links/peerRoute.ts @@ -226,6 +226,7 @@ export const makePeerRpcLayer = (input: { moveOutsideWork: true, moveFamilies: true, moveLinkLineage: true, + moveAdoptsChildren: true, threadFiling: true, outsideAgents: true, } satisfies PeerDescriptor; diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index 1f6199510..ead3087dd 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -33,7 +33,7 @@ import { sessionsThatFit, } from "./moveExport.ts"; import { carryBringsWords, threadMoveCarry } from "../orchestration/threadMoveCarry.ts"; -import { linkLineageOf } from "./familyMove.ts"; +import { linkLineageOf, startedThereOf } from "./familyMove.ts"; import { seenThroughOf } from "./roomMove.ts"; import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts"; @@ -556,6 +556,39 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { expect(linkLineageOf([frozen, child], child, MAC_MINI)).toBeUndefined(); }); + it("names only the threads it started on the target, each with the word given here (Part 3f, (g))", () => { + const record = (environmentId: EnvironmentId, threadId: string, override?: unknown) => ({ + environmentId, + label: "Mac mini", + threadId: ThreadId.make(threadId), + handle: "Agent", + title: threadId, + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: "2026-11-17T10:00:00.000Z", + ...(override !== undefined ? { override } : {}), + }); + const wrapped = { state: "done", at: "2026-11-17T09:00:00.000Z" }; + const thread = threadWith({ + childRequests: { + open: [], + deliveryEpoch: 0, + startsSinceUser: 0, + sendsSinceUser: 0, + pendingNotes: [], + remoteChildren: [ + record(MAC_MINI, "thread-wrapped", wrapped), + record(EnvironmentId.make("environment-linux"), "thread-on-linux"), + record(MAC_MINI, "thread-plain"), + ], + }, + } as never); + expect(startedThereOf(thread, MAC_MINI)).toEqual([ + { threadId: "thread-wrapped", override: wrapped }, + { threadId: "thread-plain" }, + ]); + }); + 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 28d045c6d..4af4f60c0 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -85,7 +85,12 @@ import { type ThreadMoveView, } from "../orchestration/threadMoveDecisions.ts"; import { ThreadActionGate } from "./ThreadActionGate.ts"; -import { familyManifestOf, familyThreadIdsOf, linkLineageOf } from "./familyMove.ts"; +import { + familyManifestOf, + familyThreadIdsOf, + linkLineageOf, + startedThereOf, +} from "./familyMove.ts"; import { cantComeWords, movingRoomAgents, @@ -290,6 +295,7 @@ export function takesOf(peer: PeerDescriptor): ThreadMoveTakes { ...(peer.moveOutsideWork === true ? { outsideWork: true as const } : {}), ...(peer.moveFamilies === true ? { families: true as const } : {}), ...(peer.moveLinkLineage === true ? { linkLineage: true as const } : {}), + ...(peer.moveAdoptsChildren === true ? { adoptsChildren: true as const } : {}), }; } @@ -533,6 +539,8 @@ export function targetPreviewOf( aloneRefusal: `Update Threadlines on ${peer.label} to move it without the thread that started it.`, } : {}), + // The threads it started there become its threads there again (Part 3f, (g)). + ...(peer.moveAdoptsChildren === true ? { adoptsChildren: true as const } : {}), }; } @@ -987,6 +995,7 @@ const make = Effect.gen(function* () { const remoteChildren = (thread.childRequests.remoteChildren ?? []).map((entry) => ({ label: entry.label, title: entry.title, + environmentId: entry.environmentId, })); if (parent === undefined && children.length === 0 && remoteChildren.length === 0) { return undefined; @@ -1342,6 +1351,7 @@ const make = Effect.gen(function* () { readonly kind: "complete"; readonly movedThreadId: ThreadId; readonly keptParent: boolean; + readonly adopted: ReadonlyArray; }, ) => Effect.gen(function* () { @@ -1386,6 +1396,7 @@ const make = Effect.gen(function* () { transferId, movedThreadId: step.movedThreadId, ...(step.keptParent ? { keptParent: true as const } : {}), + ...(step.adopted.length > 0 ? { adopted: [...step.adopted] } : {}), createdAt, }, ); @@ -1527,6 +1538,8 @@ const make = Effect.gen(function* () { movedThreadId: state.threadId, // That computer's own word, over the link: it kept the parent (Part 3f, (h)). keptParent: state.keptParent === true, + // And which threads it started there are its children there now (Part 3f, (g)). + adopted: state.adopted ?? [], }); } else if (state.status === "aborted") { yield* dispatchStep(threadId, transferId, { @@ -1628,6 +1641,12 @@ const make = Effect.gen(function* () { takes?.linkLineage === true && moveFamily === undefined ? linkLineageOf(threads, detail.value, targetEnvironmentId) : undefined; + // The threads it started there, for a computer that takes them back + // as its children (Part 3f, (g)). + const startedThere = + takes?.adoptsChildren === true + ? startedThereOf(detail.value, targetEnvironmentId) + : undefined; const source = { environmentId: descriptor.environmentId, environmentLabel: environment.currentLabel(), @@ -1648,6 +1667,7 @@ const make = Effect.gen(function* () { family, familyThreadIds, linkLineage, + startedThere, }); } const { place, checkout } = yield* whereFrom(detail.value, project.workspaceRoot); @@ -1658,6 +1678,7 @@ const make = Effect.gen(function* () { family, familyThreadIds, linkLineage, + startedThere, git, checkout, transferId, diff --git a/apps/server/src/moves/familyMove.ts b/apps/server/src/moves/familyMove.ts index 52d0cec3d..2ca0a0b1b 100644 --- a/apps/server/src/moves/familyMove.ts +++ b/apps/server/src/moves/familyMove.ts @@ -10,10 +10,11 @@ import type { OrchestrationThread, PeerMoveFamily, PeerMoveLinkLineage, + PeerMoveStartedThere, ThreadMoveFamily, ThreadMoveFamilyId, } from "@threadlines/contracts"; -import { PEER_MOVE_FAMILY_MAX_STAYED } from "@threadlines/contracts"; +import { PEER_MOVE_FAMILY_MAX_STAYED, PEER_MOVE_MAX_STARTED_THERE } from "@threadlines/contracts"; import { checkoutOf, type ThreadMoveView } from "../orchestration/threadMoveDecisions.ts"; @@ -152,3 +153,22 @@ export function linkLineageOf( } return { remoteParent: { threadId: parent.id, title: parent.title } }; } + +/** + * The threads `thread`'s agent started on `targetEnvironmentId`, as its + * records here hold them, for a move there (docs/design/fleet.md, Part 3f, + * (g)): each with the user's Wrap up or Reopen given here. That computer + * takes back as the thread's children only those its own records also name. + */ +export function startedThereOf( + thread: Pick, + targetEnvironmentId: EnvironmentId, +): ReadonlyArray { + return (thread.childRequests.remoteChildren ?? []) + .filter((child) => child.environmentId === targetEnvironmentId) + .slice(0, PEER_MOVE_MAX_STARTED_THERE) + .map((child) => ({ + threadId: child.threadId, + ...(child.override !== undefined ? { override: child.override } : {}), + })); +} diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts index bdf7636e5..9be554f8a 100644 --- a/apps/server/src/moves/moveExport.ts +++ b/apps/server/src/moves/moveExport.ts @@ -28,6 +28,7 @@ import type { PeerMoveRoom, PeerMoveRoomParticipant, PeerMoveScratchManifest, + PeerMoveStartedThere, PeerMoveThreadState, ThreadId, ThreadImportMessage, @@ -502,6 +503,8 @@ export interface MoveExportInput { readonly familyThreadIds?: ReadonlySet | undefined; /** It moves across the link its work came over (Part 3f, (h)): see PeerMoveLinkLineage. */ readonly linkLineage?: PeerMoveLinkLineage | undefined; + /** The threads its agent started on the target (Part 3f, (g)): see PeerMoveStartedThere. */ + readonly startedThere?: ReadonlyArray | undefined; } /** @@ -742,6 +745,9 @@ export function writeMoveExport( ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), + ...(input.startedThere !== undefined && input.startedThere.length > 0 + ? { startedThere: [...input.startedThere] } + : {}), }; yield* writeManifest(dir, manifest); return manifest; @@ -825,6 +831,9 @@ function writeSharerExport( ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), + ...(input.startedThere !== undefined && input.startedThere.length > 0 + ? { startedThere: [...input.startedThere] } + : {}), }; yield* writeManifest(input.dir, manifest); return manifest; @@ -1147,6 +1156,7 @@ export interface ScratchExportInput { readonly family?: PeerMoveFamily | undefined; readonly familyThreadIds?: ReadonlySet | undefined; readonly linkLineage?: PeerMoveLinkLineage | undefined; + readonly startedThere?: ReadonlyArray | undefined; } /** @@ -1262,6 +1272,9 @@ export function writeScratchExport( ...session.manifest, ...(input.family !== undefined ? { family: input.family } : {}), ...(input.linkLineage !== undefined ? { linkLineage: input.linkLineage } : {}), + ...(input.startedThere !== undefined && input.startedThere.length > 0 + ? { startedThere: [...input.startedThere] } + : {}), }; 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 2fe50db74..854ebc5ae 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -42,7 +42,11 @@ import { } from "@threadlines/shared/pendingRequests"; import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts"; -import { movedFromAfter, nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; +import { + adoptedFromLinkAfterLift, + movedFromAfter, + nextThreadMoveState, +} from "@threadlines/shared/threadMoveProjection"; import { withQueuedFollowUp } from "@threadlines/shared/queuedFollowUps"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts"; @@ -986,6 +990,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...existingRow.value, attachedToParent: event.payload.attached ? 1 : 0, parentAttachmentEpoch: event.payload.attachmentEpoch, + // See the in-memory projector: taken back over its link. + ...(event.payload.adoptedBy !== undefined + ? { + parentThreadId: event.payload.adoptedBy.parentThreadId, + parentTurnId: null, + remoteOrigin: null, + adoptedFromLink: event.payload.adoptedBy.fromLink, + } + : {}), }, ); return; @@ -1068,7 +1081,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti participants, // See the in-memory projector: the user here took it over. ...(event.payload.liftsMoveFence === true - ? { movedFrom: movedFromAfter(existingRow.value.movedFrom, { liftsFence: true }) } + ? { + movedFrom: movedFromAfter(existingRow.value.movedFrom, { liftsFence: true }), + adoptedFromLink: adoptedFromLinkAfterLift(existingRow.value.adoptedFromLink), + } : {}), sentModels: recordTurnModel( { ...existingRow.value, participants }, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 1c4e72762..fc488a221 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -67,6 +67,7 @@ import { ThreadMovedFrom, ThreadMoveOutcome, ThreadMoveRestore, + ThreadAdoptedFromLink, ThreadRemoteOrigin, ThreadScheduledRun, ThreadWorktreeOrigin, @@ -185,6 +186,7 @@ type ThreadLineageRow = Pick< | "movedFrom" | "lastMoveOutcome" | "moveRestoreOwed" + | "adoptedFromLink" | "historySeedOwed" | "historySeedMessageId" | "nativeSession" @@ -201,6 +203,7 @@ const threadLineageFields = (row: ThreadLineageRow) => ({ archivedWithParentAt: row.archivedWithParentAt ?? null, childRequests: row.childRequests ?? EMPTY_CHILD_REQUEST_STATE, ...(row.remoteOrigin ? { remoteOrigin: row.remoteOrigin } : {}), + ...(row.adoptedFromLink ? { adoptedFromLink: row.adoptedFromLink } : {}), ...(row.scheduledRun ? { scheduledRun: row.scheduledRun } : {}), ...(row.worktreeOrigin ? { worktreeOrigin: row.worktreeOrigin } : {}), ...(row.outsideOrigin ? { outsideOrigin: row.outsideOrigin } : {}), @@ -243,6 +246,7 @@ const shellLineageFields = (row: ThreadLineageRow) => { awaitedChildThreadCount: awaitedChildRequestCount(childRequests), pendingChildApproval: hasPendingChildApproval(childRequests), ...(row.remoteOrigin ? { remoteOrigin: row.remoteOrigin } : {}), + ...(row.adoptedFromLink ? { adoptedFromLink: row.adoptedFromLink } : {}), ...(row.scheduledRun ? { scheduledRun: row.scheduledRun } : {}), ...(row.worktreeOrigin ? { worktreeOrigin: row.worktreeOrigin } : {}), ...(row.outsideOrigin ? { outsideOrigin: row.outsideOrigin } : {}), @@ -326,6 +330,7 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( movedFrom: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMovedFrom))), lastMoveOutcome: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMoveOutcome))), moveRestoreOwed: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMoveRestore))), + adoptedFromLink: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadAdoptedFromLink))), }), ); const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields( @@ -983,6 +988,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1055,6 +1061,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1129,6 +1136,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1973,6 +1981,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -3810,6 +3819,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 29e1d9a29..07a1456e5 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -1527,6 +1527,58 @@ export function cameHomeEvents( parent: OrchestrationThread, from: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, at: string, +): ReadonlyArray { + return remoteChildGoneEvents( + readModel, + baseFor, + parent, + from, + at, + (titles, label) => + `${quotedList(titles)} moved back to this computer before it answered from ${label}. Send it the message again here.`, + ); +} + +/** + * Threads a moved parent's agent started on the computer it moved to, which + * that computer took back as the parent's children there (`adopted` on the + * move's answer, docs/design/fleet.md, Part 3f, (g)), on the parent's + * read-only copy here, in the decision that records the move: their records + * go, and the requests still open for them settle as cancelled. + */ +export function adoptedThereEvents( + readModel: OrchestrationReadModel, + baseFor: ChildEventBase, + parent: OrchestrationThread, + environmentId: EnvironmentId, + threadIds: ReadonlyArray, + at: string, +): ReadonlyArray { + return [...new Set(threadIds)].flatMap((threadId) => + remoteChildGoneEvents( + readModel, + baseFor, + parent, + { environmentId, threadId }, + at, + (titles, label) => + `${quotedList(titles)} is this thread's again on ${label}, so its answer won't come back here.`, + ), + ); +} + +/** + * A parent's record of its child on a linked computer goes, and the + * requests still open for it there settle as cancelled with `words`. None + * when the parent holds no such record. + */ +function remoteChildGoneEvents( + readModel: OrchestrationReadModel, + baseFor: ChildEventBase, + parent: OrchestrationThread, + from: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + at: string, + words: (titles: ReadonlyArray, label: string) => string, ): ReadonlyArray { const record = (parent.childRequests.remoteChildren ?? []).find( (entry) => entry.environmentId === from.environmentId && entry.threadId === from.threadId, @@ -1538,15 +1590,8 @@ export function cameHomeEvents( (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.`, + ...settleOpenRequests(readModel, baseFor, parent, open, "cancelled", at, (titles) => + words(titles, record.label), ), { ...baseFor(parent.id), diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 1d4048fa2..36e13b1e3 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -37,7 +37,7 @@ import { describe, expect, it } from "vite-plus/test"; import { linkMoveCopyThreadId } from "../moves/linkMoveIds.ts"; import { decideOrchestrationCommand } from "./decider.ts"; import { createEmptyReadModel, projectEvent } from "./projector.ts"; -import { isLinkFenced } from "./linkFence.ts"; +import { isLinkFenced, turnLiftsMoveFence } from "./linkFence.ts"; import { messageSentFromSession } from "./messageSentFrom.ts"; import { threadMoveGuardRefusal, threadMoveRefusals } from "./threadMoveDecisions.ts"; @@ -3689,3 +3689,296 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h)) }); }); }); + +describe("a parent arriving beside threads it started here (Part 3f, (g))", () => { + const LINK = "device-mac-mini"; + const SOURCE = ThreadId.make("thread-parent-on-mac"); + const ARRIVED = ThreadId.make("thread-parent-arrived"); + const STARTED = ThreadId.make("thread-started-here"); + const THIRD = { environmentId: EnvironmentId.make("environment-third"), label: "Linux box" }; + const TAKES: ThreadMoveTakes = { threadState: true, families: true, linkLineage: true }; + const origin = (extra: Record = {}) => ({ + linkDeviceId: LINK, + environmentId: MAC_MINI.environmentId, + environmentPinned: true, + environmentLabel: "Mac mini", + threadId: SOURCE, + threadTitle: "Ship it", + ...extra, + }); + /** A thread the link started here for SOURCE, before SOURCE moved here. */ + const startedHere = async ( + model: OrchestrationReadModel, + threadId: ThreadId = STARTED, + extra: Record = {}, + ) => + ( + await apply(model, { + type: "thread.create", + commandId: nextCommandId(), + threadId, + projectId: PROJECT, + title: "Fix tests", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${threadId}`, + remoteOrigin: origin(), + createdAt: now, + ...extra, + } as OrchestrationCommand) + ).model; + const arrive = ( + children: ReadonlyArray<{ readonly threadId: ThreadId; readonly override?: unknown }>, + extra: Record = {}, + ): OrchestrationCommand => + ({ + type: "thread.import", + commandId: nextCommandId(), + threadId: ARRIVED, + projectId: PROJECT, + title: "Ship it", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "ship", + worktreePath: `/worktrees/${ARRIVED}`, + movedFrom: { ...MAC_MINI, environmentPinned: true, threadId: SOURCE, movedAt: now }, + messages: [], + activities: [], + adoptsChildren: { linkDeviceId: LINK, children }, + createdAt: now, + ...extra, + }) as OrchestrationCommand; + const sends = (threadId: ThreadId, id: string, extra: Record = {}) => + ({ + type: "thread.turn.start", + commandId: nextCommandId(), + threadId, + message: { messageId: MessageId.make(id), role: "user", text: "Go", attachments: [] }, + sentFrom: { kind: "computer", place: "here" }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + ...extra, + }) as OrchestrationCommand; + const boundaryOf = (model: OrchestrationReadModel) => + threadOf(model, ARRIVED).activities.find((entry) => entry.kind === "thread.moved-in") + ?.payload as { + readonly brought?: ReadonlyArray; + readonly left: ReadonlyArray; + }; + + it("takes a thread it started here back as its child, fenced until a person writes in it", async () => { + const { model, refusal } = await apply( + await startedHere(await seeded()), + arrive([{ threadId: STARTED }]), + ); + expect(refusal).toBeNull(); + const child = threadOf(model, STARTED); + expect(child).toMatchObject({ + parentThreadId: ARRIVED, + parentTurnId: null, + attachedToParent: true, + parentAttachmentEpoch: 1, + adoptedFromLink: { environmentId: MAC_MINI.environmentId, label: "Mac mini", fenced: true }, + }); + expect(child.remoteOrigin ?? null).toBeNull(); + expect(isLinkFenced(child)).toBe(true); + expect(child.activities.at(-1)?.kind).toBe("thread.adopted-by-moved-parent"); + expect(boundaryOf(model).brought).toContain( + "Its thread 'Fix tests' was already on this computer. It's this thread's again.", + ); + }); + + it("leaves each thread that doesn't qualify as it is, says why, and still lands", async () => { + const OTHER_PROJECT = ProjectId.make("project-2"); + let model = await seeded(); + ({ model } = await apply(model, { + type: "project.create", + commandId: nextCommandId(), + projectId: OTHER_PROJECT, + title: "Other", + workspaceRoot: "/other", + createdAt: now, + })); + const cases = [ + { remoteOrigin: origin({ linkDeviceId: "device-someone-else" }) }, + { remoteOrigin: origin({ threadId: ThreadId.make("thread-other-on-mac") }) }, + { remoteOrigin: origin({ environmentPinned: false }) }, + { projectId: OTHER_PROJECT }, + {}, + {}, + ]; + const ids = cases.map((_, index) => ThreadId.make(`thread-case-${index}`)); + for (const [index, extra] of cases.entries()) { + model = await startedHere(model, ids[index], { ...extra, title: `Case ${index}` }); + } + ({ model } = await apply(model, { + type: "thread.archive", + commandId: nextCommandId(), + threadId: ids[4], + createdAt: now, + } as OrchestrationCommand)); + const queued = await apply(model, { + type: "thread.move.queue", + commandId: nextCommandId(), + threadId: ids[5]!, + requestId: ThreadMoveRequestId.make("request-moving"), + target: MAC_MINI, + agent: modelSelection, + mode: "when-done", + requestedBy: { kind: "user" }, + targetTakes: TAKES, + createdAt: now, + }); + expect(queued.refusal).toBeNull(); + model = queued.model; + + let refusal: string | null; + ({ model, refusal } = await apply(model, arrive(ids.map((threadId) => ({ threadId }))))); + expect(refusal).toBeNull(); + for (const threadId of ids) { + expect(threadOf(model, threadId).parentThreadId).toBeNull(); + expect(threadOf(model, threadId).remoteOrigin ?? null).not.toBeNull(); + } + expect(boundaryOf(model).brought ?? []).toEqual([]); + const line = (index: number, why: string) => + `Its thread 'Case ${index}' is already on this computer. It stays separate because ${why}, so this thread can't reach it.`; + expect(boundaryOf(model).left).toEqual( + expect.arrayContaining([ + line(0, "this computer can't confirm this thread started it"), + line(1, "this computer can't confirm this thread started it"), + line(2, "this computer can't confirm this thread started it"), + line(3, "it's in another project here"), + line(4, "it's archived"), + line(5, "it's moving"), + ]), + ); + }); + + it("never takes back a thread with more access than the parent has here, nor lowers it", async () => { + const { model, refusal } = await apply( + await startedHere(await seeded()), + arrive([{ threadId: STARTED }], { interactionMode: "plan" }), + ); + expect(refusal).toBeNull(); + const child = threadOf(model, STARTED); + expect(child.parentThreadId).toBeNull(); + expect(child).toMatchObject({ runtimeMode: "auto", interactionMode: "default" }); + expect(boundaryOf(model).left).toContain( + "Its thread 'Fix tests' is already on this computer. It stays separate because it has more access than this thread has here, so this thread can't reach it.", + ); + }); + + it("a Wrap up given there stands only when it is newer than the word given here", async () => { + const LATER = ThreadId.make("thread-started-later"); + let model = await startedHere(await startedHere(await seeded()), LATER, { title: "Review" }); + ({ model } = await apply(model, { + type: "thread.done-override.set", + commandId: nextCommandId(), + threadId: STARTED, + state: "active", + at: "2026-10-22T09:30:00.000Z", + } as OrchestrationCommand)); + const older = { state: "done", at: "2026-10-22T09:00:00.000Z" }; + ({ model } = await apply( + model, + arrive([ + { threadId: STARTED, override: older }, + { threadId: LATER, override: older }, + ]), + )); + expect(threadOf(model, STARTED).doneOverride).toEqual({ + state: "active", + at: "2026-10-22T09:30:00.000Z", + }); + expect(threadOf(model, LATER).doneOverride).toEqual(older); + expect(boundaryOf(model).brought).toContain( + "Its 2 threads already on this computer are this thread's again: Fix tests, Review.", + ); + }); + + it("only a person's message in the child lifts its fence, and until then it goes only home", async () => { + let { model } = await apply(await startedHere(await seeded()), arrive([{ threadId: STARTED }])); + const third = await apply(model, { + type: "thread.move.queue", + commandId: nextCommandId(), + threadId: STARTED, + requestId: ThreadMoveRequestId.make("request-third"), + target: THIRD, + agent: modelSelection, + mode: "when-done", + requestedBy: { kind: "user" }, + targetTakes: TAKES, + createdAt: now, + }); + expect(third.refusal).toContain( + "This thread was started by an agent on Mac mini, and until you send it a message here it can only move back to Mac mini.", + ); + // A scheduled run, or a message from another thread: still fenced. + const decided = await Effect.runPromise( + decideOrchestrationCommand({ + readModel: model, + command: sends(STARTED, "m-scheduled", { scheduledTaskId: "task-1" }), + }), + ); + const planned = Array.isArray(decided) ? decided : [decided]; + const requested = planned.find((event) => event.type === "thread.turn-start-requested"); + expect(requested?.payload).not.toHaveProperty("liftsMoveFence"); + expect( + turnLiftsMoveFence(threadOf(model, STARTED), { + sentFrom: { kind: "computer", place: "here" }, + fromThread: { threadId: ARRIVED, requestId: ChildRequestId.make("ask"), kind: "request" }, + message: { messageId: MessageId.make("m-from-thread") }, + }), + ).toBe(false); + // A person's message in the parent lifts the parent's fence, not the child's. + ({ model } = await apply(model, sends(ARRIVED, "m-parent"))); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + expect(threadOf(model, STARTED).adoptedFromLink?.fenced).toBe(true); + ({ model } = await apply(model, sends(STARTED, "m-person"))); + expect(threadOf(model, STARTED).adoptedFromLink).toMatchObject({ fenced: false }); + expect(isLinkFenced(threadOf(model, STARTED))).toBe(false); + }); + + it("the copy that moved away stops keeping only the threads that became its children there", async () => { + let { model } = await apply(await seeded(), startMove()); + const record = (environment: typeof MAC_MINI, threadId: string) => + project(model, "thread.remote-child-updated", { + threadId: THREAD, + child: { + ...environment, + threadId: ThreadId.make(threadId), + handle: "Agent", + title: threadId, + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: now, + }, + updatedAt: now, + }); + model = await record(MAC_MINI, "thread-adopted"); + model = await record(MAC_MINI, "thread-kept-apart"); + model = await record(THIRD, "thread-adopted"); + ({ model } = await apply(model, { + type: "thread.move.complete", + commandId: nextCommandId(), + threadId: THREAD, + transferId: TRANSFER, + movedThreadId: ThreadId.make("thread-there"), + adopted: [ThreadId.make("thread-adopted")], + createdAt: now, + })); + expect( + (threadOf(model).childRequests.remoteChildren ?? []).map((entry) => [ + entry.environmentId, + entry.threadId, + ]), + ).toEqual([ + [MAC_MINI.environmentId, "thread-kept-apart"], + [THIRD.environmentId, "thread-adopted"], + ]); + }); +}); diff --git a/apps/server/src/orchestration/linkFence.ts b/apps/server/src/orchestration/linkFence.ts index 272333629..781a81bdf 100644 --- a/apps/server/src/orchestration/linkFence.ts +++ b/apps/server/src/orchestration/linkFence.ts @@ -1,42 +1,55 @@ /** * The linked-computer fence (docs/design/fleet.md, "Fence"): work that came * from another computer gets no Threadlines tools here, so it can't reach - * other threads, schedules or this computer's settings. Two kinds of thread - * work behind it: one another computer's agent started here (`remoteOrigin`), - * for good, and one that moved here (`movedFrom.fenced`, Part 3e), until a - * message the user sends here starts a turn in it. Every place the fence - * applies asks this one rule. + * other threads, schedules or this computer's settings. Three kinds of + * thread work behind it: one another computer's agent started here + * (`remoteOrigin`), for good; one that moved here (`movedFrom.fenced`, Part + * 3e); and one another computer's agent started here that became a child + * here when that agent's thread moved here (`adoptedFromLink.fenced`, Part + * 3f, (g)). The last two until a message the user sends here starts a turn + * in them (Will's call for the third: the same rule as a moved thread). + * Every place the fence applies asks this one rule. */ import type { MessageId, OrchestrationCommand, OrchestrationThread } from "@threadlines/contracts"; -export type LinkFencedThread = Pick; +export type LinkFencedThread = Pick< + OrchestrationThread, + "remoteOrigin" | "movedFrom" | "adoptedFromLink" +>; /** Whether the thread works behind the fence. */ export const isLinkFenced = (thread: LinkFencedThread): boolean => - (thread.remoteOrigin ?? null) !== null || thread.movedFrom?.fenced === true; + (thread.remoteOrigin ?? null) !== null || + thread.movedFrom?.fenced === true || + thread.adoptedFromLink?.fenced === true; type TurnStartCommand = Extract; /** - * Whether a turn start lifts a moved thread's fence: only one whose message a - * person sent from the app, which `sentFrom` proves (the server alone stamps - * it, from the connection's sign-in; see withMessageSentFrom). An allow-list, - * so whatever else starts a turn (command output, pull request auto-fix, a - * restart or usage-limit continue, a retry, another thread, an outside agent, - * a scheduled task) carries no `sentFrom` and leaves the fence up. A message - * the move carried (`imported`) or Threadlines wrote for it (`afterMove`) - * never lifts it either, whatever it carries. Nor does anything lift it on a - * thread another computer's agent directs (`remoteOrigin`): a child that - * moved there without its parent is fenced for good (Part 3f, (h)). + * Whether a turn start lifts a moved or adopted thread's fence: only one + * whose message a person sent from the app, which `sentFrom` proves (the + * server alone stamps it, from the connection's sign-in; see + * withMessageSentFrom). An allow-list, so whatever else starts a turn + * (command output, pull request auto-fix, a restart or usage-limit continue, + * a retry, another thread, an outside agent, a scheduled task) carries no + * `sentFrom` and leaves the fence up. A message the move carried (`imported`) + * or Threadlines wrote for it (`afterMove`) never lifts it either, whatever + * it carries. Nor does anything lift it on a thread another computer's agent + * directs (`remoteOrigin`): a child that moved there without its parent is + * fenced for good (Part 3f, (h)). The lift clears both markers. */ export function turnLiftsMoveFence( - thread: Pick, + thread: Pick< + OrchestrationThread, + "movedFrom" | "adoptedFromLink" | "messages" | "queuedFollowUps" | "remoteOrigin" + >, command: Pick< TurnStartCommand, "sentFrom" | "fromThread" | "fromOutside" | "scheduledTaskId" | "trigger" > & { readonly message: { readonly messageId: MessageId } }, ): boolean { - if (thread.movedFrom?.fenced !== true || command.sentFrom === undefined) return false; + const fenced = thread.movedFrom?.fenced === true || thread.adoptedFromLink?.fenced === true; + if (!fenced || command.sentFrom === undefined) return false; if ((thread.remoteOrigin ?? null) !== null) return false; if ( command.fromThread !== undefined || @@ -60,7 +73,11 @@ export function turnLiftsMoveFence( /** Why a fenced thread's agent can't use `tools` ("thread tools", "schedule tools"), in its words. */ export function linkFenceRefusal(thread: LinkFencedThread, tools: string): string { - return (thread.remoteOrigin ?? null) !== null - ? `This thread was started by an agent on another computer, so it has no ${tools}.` - : `This thread moved here from ${thread.movedFrom?.label ?? "another computer"}, so it has no ${tools} until the user here sends it a message.`; + if ((thread.remoteOrigin ?? null) !== null) { + return `This thread was started by an agent on another computer, so it has no ${tools}.`; + } + if (thread.movedFrom?.fenced !== true && thread.adoptedFromLink?.fenced === true) { + return `This thread was started by an agent on ${thread.adoptedFromLink.label}, so it has no ${tools} until the user here sends it a message.`; + } + return `This thread moved here from ${thread.movedFrom?.label ?? "another computer"}, so it has no ${tools} until the user here sends it a message.`; } diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index b750cb4f6..655b5c53a 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -36,7 +36,11 @@ import { withUnqueuedAgentMessage, } from "@threadlines/shared/roomAgentRequests"; import { applyAgentPagePublication } from "@threadlines/shared/agentPages"; -import { movedFromAfter, nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; +import { + adoptedFromLinkAfterLift, + movedFromAfter, + nextThreadMoveState, +} from "@threadlines/shared/threadMoveProjection"; import { withQueuedFollowUp } from "@threadlines/shared/queuedFollowUps"; import { applyCommandRequestDismissed, @@ -1179,6 +1183,16 @@ export function projectEvent( threads: updateThread(nextBase.threads, payload.threadId, { attachedToParent: payload.attached, parentAttachmentEpoch: payload.attachmentEpoch, + // Taken back by the thread that started it over a link, which + // moved here (ThreadAdoptedFromLink): this computer's child now. + ...(payload.adoptedBy !== undefined + ? { + parentThreadId: payload.adoptedBy.parentThreadId, + parentTurnId: null, + remoteOrigin: null, + adoptedFromLink: payload.adoptedBy.fromLink, + } + : {}), }), })), ); @@ -1237,7 +1251,10 @@ export function projectEvent( participants, // The user here took a thread that moved here over: its fence lifts. ...(payload.liftsMoveFence === true - ? { movedFrom: movedFromAfter(thread.movedFrom, { liftsFence: true }) } + ? { + movedFrom: movedFromAfter(thread.movedFrom, { liftsFence: true }), + adoptedFromLink: adoptedFromLinkAfterLift(thread.adoptedFromLink), + } : {}), // What the turn is sent with, and its messages stamped with. sentModels: recordTurnModel( diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 1cc1bc4af..1e5e19197 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -21,6 +21,7 @@ import { type OrchestrationReadModel, type OrchestrationQueuedFollowUp, type OrchestrationThread, + type OrchestrationThreadDoneOverride, type OrchestrationThreadMove, type ThreadId, type ThreadMoveFamily, @@ -37,6 +38,7 @@ import { type ThreadNativeSessionFellBackPayload, type ThreadPendingMove, } from "@threadlines/contracts"; +import { withinModeCeiling } from "@threadlines/shared/childThreads"; import { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { threadPullRequestAutomationArmed } from "@threadlines/shared/linkedPullRequests"; import { @@ -52,7 +54,13 @@ import { arrivalMessageText, resumedGoalMessageText } from "../moves/arrivalMess import { linkMoveCopyThreadId } from "../moves/linkMoveIds.ts"; import { decideAgentChainStop } from "./agentRequestDecisions.ts"; import { derivedUuid } from "./childRequestIds.ts"; -import { cameHomeEvents, leftBehindEvents, movedAloneEvents } from "./childThreadDecisions.ts"; +import { + adoptedThereEvents, + attachedChildrenOf, + cameHomeEvents, + leftBehindEvents, + movedAloneEvents, +} from "./childThreadDecisions.ts"; import { hasBackgroundWork } from "./sessionBackgroundTasks.ts"; import { drainsWhileMoveWaits, @@ -573,17 +581,28 @@ export function remoteOriginMoveRefusal( * is (`environmentPinned`), where it came from is only the sender's word, so * it goes nowhere. Once a person here takes it over, the usual rules hold. A * null `target` asks about any computer: the dialog says per computer. + * + * The same holds for a thread another computer's agent started here that + * its parent took back when it moved here (`adoptedFromLink.fenced`, Part + * 3f, (g)): it goes back to that computer only, which its link proved. */ export function fencedMoveRefusal( - thread: Pick, + thread: Pick, target: ThreadMoveTarget | null, ): string | null { + if (target === null) return null; const from = thread.movedFrom ?? null; - if (from === null || from.fenced !== true || target === null) return null; - if (from.environmentPinned !== true) { - return `This thread moved here from ${from.label}, and this computer's link can't confirm which computer that is, so it stays here until you send it a message.`; + if (from !== null && from.fenced === true) { + if (from.environmentPinned !== true) { + return `This thread moved here from ${from.label}, and this computer's link can't confirm which computer that is, so it stays here until you send it a message.`; + } + if (target.environmentId !== from.environmentId) return fencedElsewhereWords(from.label); } - return target.environmentId === from.environmentId ? null : fencedElsewhereWords(from.label); + const adopted = thread.adoptedFromLink ?? null; + if (adopted !== null && adopted.fenced && target.environmentId !== adopted.environmentId) { + return `This thread was started by an agent on ${adopted.label}, and until you send it a message here it can only move back to ${adopted.label}.`; + } + return null; } /** The words for a fenced moved thread, moving anywhere but back where it came from. */ @@ -1477,9 +1496,11 @@ 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)). 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)). + * same decision (docs/design/fleet.md, Part 3f, (g)), and the threads it + * started on that computer that are its children there now (`adopted`) + * leave its records. 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, @@ -1506,7 +1527,7 @@ function moveCompleteEvents( move: OrchestrationThreadMove, command: Pick< CommandOf<"thread.move.complete">, - "transferId" | "movedThreadId" | "keptParent" | "createdAt" + "transferId" | "movedThreadId" | "keptParent" | "adopted" | "createdAt" >, baseFor: EventBase, returned?: "adopted", @@ -1540,6 +1561,15 @@ function moveCompleteEvents( }, ...readOnlyCopyEvents(thread, command.createdAt, baseFor), ...leftBehind, + // Its threads on that computer that are its children there now (Part 3f, (g)). + ...adoptedThereEvents( + readModel, + baseFor, + thread, + move.target.environmentId, + command.adopted ?? [], + command.createdAt, + ), ...(move.family === undefined ? movedAloneEvents( readModel, @@ -1672,6 +1702,7 @@ export function decideThreadImport( if (familyRefusal !== null) return refuse(familyRefusal); const linkRefusal = importedLinkLineageRefusal(readModel, command); if (linkRefusal !== null) return refuse(linkRefusal); + const adoption = importedAdoption(readModel, command); // 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). @@ -1794,8 +1825,10 @@ export function decideThreadImport( payload: { threadId: command.threadId, activity: { ...activity, turnId: null } }, })); const arrival = command.arrival; + const brought = [...(arrival?.brought ?? []), ...adoption.brought]; const left = [ ...(arrival?.left ?? []), + ...adoption.left, command.remoteOrigin !== undefined ? remoteParentFenceWords(command.remoteOrigin) : MOVED_FENCE_WORDS, @@ -1818,9 +1851,7 @@ export function decideThreadImport( // Which the agent got: its own session, or (absent) a summary. ...(command.nativeSession !== undefined ? { nativeSession: command.nativeSession } : {}), // What came along, and what didn't, in plain words. - ...(arrival !== undefined && arrival.brought.length > 0 - ? { brought: arrival.brought } - : {}), + ...(brought.length > 0 ? { brought } : {}), left, }, turnId: null, @@ -1869,11 +1900,200 @@ export function decideThreadImport( ...activities, ...importedState(command, base), boundary, + ...adoptedEvents(command, adoption.adopted, baseFor), ...cameHome, ...completed, ]; } +/** At most this many titles a "Moved here" line names. */ +const ADOPTED_TITLES_NAMED = 10; + +const titlesOf = (threads: ReadonlyArray<{ readonly title: string }>) => + threads + .slice(0, ADOPTED_TITLES_NAMED) + .map((thread) => thread.title) + .join(", "); + +/** + * Which of the threads here that the arriving thread's agent started over + * its link (`adoptsChildren`, docs/design/fleet.md, Part 3f, (g)) become its + * children, and the "Moved here" words for them and for the ones that stay + * apart. Never refuses the import: a thread that doesn't qualify stays as it + * is, with why. One gone meanwhile is left out of the words. + */ +function importedAdoption( + readModel: OrchestrationReadModel, + command: CommandOf<"thread.import">, +): { + readonly adopted: ReadonlyArray<{ + readonly thread: OrchestrationThread; + readonly override: OrchestrationThreadDoneOverride | undefined; + }>; + readonly brought: ReadonlyArray; + readonly left: ReadonlyArray; +} { + const asked = command.adoptsChildren; + // Only a thread arriving on its own takes threads as its children here. + if ( + asked === undefined || + command.lineage !== undefined || + command.remoteOrigin !== undefined || + command.adopt !== undefined + ) { + return { adopted: [], brought: [], left: [] }; + } + const adopted: Array<{ + readonly thread: OrchestrationThread; + readonly override: OrchestrationThreadDoneOverride | undefined; + }> = []; + const apart: Array<{ readonly title: string; readonly why: string }> = []; + const seen = new Set(); + for (const entry of asked.children) { + if (seen.has(entry.threadId)) continue; + seen.add(entry.threadId); + const child = readModel.threads.find((thread) => thread.id === entry.threadId); + if (child === undefined || child.deletedAt !== null) continue; + const why = adoptionRefusal(readModel, command, asked.linkDeviceId, child); + if (why === null) adopted.push({ thread: child, override: entry.override }); + else apart.push({ title: child.title, why }); + } + const [only] = adopted; + const brought = + adopted.length === 0 + ? [] + : [ + adopted.length === 1 && only !== undefined + ? `Its thread '${only.thread.title}' was already on this computer. It's this thread's again.` + : `Its ${adopted.length} threads already on this computer are this thread's again: ${titlesOf(adopted.map((entry) => entry.thread))}.`, + ]; + const left = apart.map( + (entry) => + `Its thread '${entry.title}' is already on this computer. It stays separate because ${entry.why}, so this thread can't reach it.`, + ); + return { adopted, brought, left }; +} + +/** + * Why `child`, a thread here, can't become the arriving thread's child, in + * words that finish "It stays separate because ...", or null. It must be + * one this very link started for the very thread that arrives, from the + * computer that link proved it is; in the arriving thread's project; not + * archived, moving or a parent itself; and asking no more access than the + * arriving thread has here (its modes as this import writes them): a child + * never has more access than its parent, and its access is never lowered + * for it. + */ +function adoptionRefusal( + readModel: OrchestrationReadModel, + command: CommandOf<"thread.import">, + linkDeviceId: string, + child: OrchestrationThread, +): string | null { + const origin = child.remoteOrigin ?? null; + if ( + origin === null || + origin.linkDeviceId !== linkDeviceId || + origin.threadId !== command.movedFrom.threadId || + origin.environmentPinned !== true || + command.movedFrom.environmentPinned !== true || + origin.environmentId !== command.movedFrom.environmentId + ) { + return "this computer can't confirm this thread started it"; + } + if (child.projectId !== command.projectId) return "it's in another project here"; + if (child.archivedAt !== null) return "it's archived"; + if ((child.move ?? null) !== null || (child.pendingMove ?? null) !== null) { + return "it's moving"; + } + if ( + (child.parentThreadId !== null && child.attachedToParent) || + attachedChildrenOf(readModel, child.id).length > 0 + ) { + return "it's in another family here"; + } + if ( + !withinModeCeiling(child, { + runtimeMode: command.runtimeMode, + interactionMode: command.interactionMode, + }) + ) { + return "it has more access than this thread has here"; + } + return null; +} + +/** + * Each adopted thread becomes the arriving thread's child (no parent turn, a + * fresh attachment epoch, so nothing owed under its old one comes back), + * stops being the other computer's (`remoteOrigin` goes) and works fenced + * until the user here sends it a message (`adoptedFromLink`). The user's + * Wrap up or Reopen given there stands when it is newer than the one here + * (the rule `fromLinkedComputer` follows). Its timeline says what happened. + */ +function adoptedEvents( + command: CommandOf<"thread.import">, + adopted: ReadonlyArray<{ + readonly thread: OrchestrationThread; + readonly override: OrchestrationThreadDoneOverride | undefined; + }>, + baseFor: EventBase, +): PlannedEvent[] { + const at = command.createdAt; + const label = command.movedFrom.label; + return adopted.flatMap(({ thread, override }): PlannedEvent[] => { + const epoch = thread.parentAttachmentEpoch + 1; + const newer = + override !== undefined && + (thread.doneOverride === null || + Date.parse(thread.doneOverride.at) < Date.parse(override.at)); + return [ + { + ...baseFor(thread.id), + type: "thread.parent-attachment-set", + payload: { + threadId: thread.id, + attached: true, + attachmentEpoch: epoch, + at, + adoptedBy: { + parentThreadId: command.threadId, + fromLink: { environmentId: command.movedFrom.environmentId, label, fenced: true }, + }, + }, + }, + ...(newer + ? [ + { + ...baseFor(thread.id), + type: "thread.done-override-set" as const, + payload: { threadId: thread.id, state: override.state, at: override.at }, + }, + ] + : []), + { + ...baseFor(thread.id), + type: "thread.activity-appended", + payload: { + threadId: thread.id, + activity: { + id: EventId.make(`adopted-by-moved-parent:${thread.id}:${epoch}`), + tone: "info", + kind: AdoptedByMovedParentActivityKind, + summary: `'${command.title}' moved here from ${label}, and this is its thread again. Its agent can't use other threads, rooms or schedules here until you send it a message.`, + payload: { parentThreadId: command.threadId, fromLabel: label }, + turnId: null, + createdAt: at, + }, + }, + }, + ]; + }); +} + +/** Activity on a thread its parent took back when it moved here (Part 3f, (g)). */ +export const AdoptedByMovedParentActivityKind = "thread.adopted-by-moved-parent"; + /** * 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 diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 141832d4c..4a41ce727 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -10,6 +10,7 @@ import { DeleteProjectionThreadInput, GetProjectionThreadInput, ListProjectionThreadsByProjectInput, + ListProjectionAdoptedChildrenInput, ListProjectionThreadsByRemoteLinkInput, ProjectionSideTurnsJson, ProjectionThread, @@ -34,6 +35,7 @@ import { ThreadMovedFrom, ThreadMoveOutcome, ThreadMoveRestore, + ThreadAdoptedFromLink, ThreadRemoteOrigin, OrchestrationOutsideWork, OutsideAgentRef, @@ -71,6 +73,7 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields( movedFrom: Schema.NullOr(Schema.fromJsonString(ThreadMovedFrom)), lastMoveOutcome: Schema.NullOr(Schema.fromJsonString(ThreadMoveOutcome)), moveRestoreOwed: Schema.NullOr(Schema.fromJsonString(ThreadMoveRestore)), + adoptedFromLink: Schema.NullOr(Schema.fromJsonString(ThreadAdoptedFromLink)), roomContext: Schema.fromJsonString( Schema.Record(Schema.String, OrchestrationRoomContextCursor), ), @@ -136,6 +139,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { moved_from_json, last_move_outcome_json, move_restore_owed_json, + adopted_from_link_json, history_seed_owed, history_seed_message_id, native_session, @@ -207,6 +211,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.movedFrom ? JSON.stringify(row.movedFrom) : null}, ${row.lastMoveOutcome ? JSON.stringify(row.lastMoveOutcome) : null}, ${row.moveRestoreOwed ? JSON.stringify(row.moveRestoreOwed) : null}, + ${row.adoptedFromLink ? JSON.stringify(row.adoptedFromLink) : null}, ${row.historySeedOwed ?? 0}, ${row.historySeedMessageId ?? null}, ${row.nativeSession ?? null}, @@ -270,6 +275,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { moved_from_json = excluded.moved_from_json, last_move_outcome_json = excluded.last_move_outcome_json, move_restore_owed_json = excluded.move_restore_owed_json, + adopted_from_link_json = excluded.adopted_from_link_json, history_seed_owed = excluded.history_seed_owed, history_seed_message_id = excluded.history_seed_message_id, native_session = excluded.native_session, @@ -340,6 +346,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -412,6 +419,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", move_restore_owed_json AS "moveRestoreOwed", + adopted_from_link_json AS "adoptedFromLink", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -444,6 +452,19 @@ const makeProjectionThreadRepository = Effect.gen(function* () { `, }); + const listAdoptedChildIdsRows = SqlSchema.findAll({ + Request: ListProjectionAdoptedChildrenInput, + Result: Schema.Struct({ threadId: ThreadId }), + execute: ({ parentThreadId }) => + sql` + SELECT thread_id AS "threadId" + FROM projection_threads + WHERE parent_thread_id = ${parentThreadId} + AND adopted_from_link_json IS NOT NULL + ORDER BY created_at ASC, thread_id ASC + `, + }); + const deleteProjectionThreadRow = SqlSchema.void({ Request: DeleteProjectionThreadInput, execute: ({ threadId }) => @@ -476,6 +497,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ), ); + const listAdoptedChildIds: ProjectionThreadRepositoryShape["listAdoptedChildIds"] = (input) => + listAdoptedChildIdsRows(input).pipe( + Effect.map((rows) => rows.map((row) => row.threadId)), + Effect.mapError( + toPersistenceSqlError("ProjectionThreadRepository.listAdoptedChildIds:query"), + ), + ); + const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) => deleteProjectionThreadRow(input).pipe( Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.deleteById:query")), @@ -486,6 +515,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { getById, listByProjectId, listIdsByRemoteLink, + listAdoptedChildIds, deleteById, } satisfies ProjectionThreadRepositoryShape; }); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 2cde8cfdb..50dee9f56 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -139,6 +139,7 @@ import Migration0116 from "./Migrations/116_ProjectLeadThread.ts"; import Migration0117 from "./Migrations/117_ThreadMoveCarry.ts"; import Migration0118 from "./Migrations/118_SessionStopRequestedTurn.ts"; import Migration0119 from "./Migrations/119_LinkMoveFamilies.ts"; +import Migration0120 from "./Migrations/120_ThreadAdoptedFromLink.ts"; /** * Migration loader with all migrations defined inline. @@ -270,6 +271,7 @@ export const migrationEntries = [ [117, "ThreadMoveCarry", Migration0117], [118, "SessionStopRequestedTurn", Migration0118], [119, "LinkMoveFamilies", Migration0119], + [120, "ThreadAdoptedFromLink", Migration0120], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/120_ThreadAdoptedFromLink.ts b/apps/server/src/persistence/Migrations/120_ThreadAdoptedFromLink.ts new file mode 100644 index 000000000..eb0fff8f4 --- /dev/null +++ b/apps/server/src/persistence/Migrations/120_ThreadAdoptedFromLink.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * A thread another computer's agent started here becomes that agent's + * thread's child when that thread moves here (docs/design/fleet.md, Part 3f, + * (g)): `projection_threads.adopted_from_link_json` holds where it was + * started from and whether it is still fenced + * (`OrchestrationThread.adoptedFromLink`), null for every other thread. + * + * A new nullable column; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE projection_threads ADD COLUMN adopted_from_link_json TEXT`; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 0fb9b7db4..6a34a0ce6 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -37,6 +37,7 @@ import { ThreadNativeSession, ThreadMoveOutcome, ThreadMoveRestore, + ThreadAdoptedFromLink, ThreadRemoteOrigin, OrchestrationOutsideWork, OutsideAgentRef, @@ -191,6 +192,8 @@ export const ProjectionThread = Schema.Struct({ archivedWithParentAt: Schema.optional(Schema.NullOr(IsoDateTime)), /** See `OrchestrationThread.remoteOrigin`. Absent or null reads as none. */ remoteOrigin: Schema.optional(Schema.NullOr(ThreadRemoteOrigin)), + /** See `OrchestrationThread.adoptedFromLink`. Absent or null reads as none. */ + adoptedFromLink: Schema.optional(Schema.NullOr(ThreadAdoptedFromLink)), /** See `OrchestrationThread.scheduledRun`. Absent or null reads as none. */ scheduledRun: Schema.optional(Schema.NullOr(ThreadScheduledRun)), /** See `OrchestrationThread.worktreeOrigin`. Absent or null reads as none. */ @@ -263,6 +266,11 @@ export const ListProjectionThreadsByRemoteLinkInput = Schema.Struct({ export type ListProjectionThreadsByRemoteLinkInput = typeof ListProjectionThreadsByRemoteLinkInput.Type; +export const ListProjectionAdoptedChildrenInput = Schema.Struct({ + parentThreadId: ThreadId, +}); +export type ListProjectionAdoptedChildrenInput = typeof ListProjectionAdoptedChildrenInput.Type; + /** * ProjectionThreadRepositoryShape - Service API for projected thread records. */ @@ -298,6 +306,14 @@ export interface ProjectionThreadRepositoryShape { input: ListProjectionThreadsByRemoteLinkInput, ) => Effect.Effect, ProjectionRepositoryError>; + /** + * Ids of `parentThreadId`'s children that it took back over a link when it + * moved here (`adoptedFromLink`), deleted ones included. + */ + readonly listAdoptedChildIds: ( + input: ListProjectionAdoptedChildrenInput, + ) => Effect.Effect, ProjectionRepositoryError>; + /** * Soft-delete a projected thread row by id. */ diff --git a/apps/web/src/components/ThreadMoveDialogContent.tsx b/apps/web/src/components/ThreadMoveDialogContent.tsx index 48d37ce4c..c52af630c 100644 --- a/apps/web/src/components/ThreadMoveDialogContent.tsx +++ b/apps/web/src/components/ThreadMoveDialogContent.tsx @@ -416,7 +416,7 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread (family.children.length > 0 || family.remoteChildren.length > 0) ? ( ; - readonly targetLabel: string; + readonly target: ThreadMoveTargetPreview; readonly staying: ReadonlySet; readonly comingCount: number; readonly disabled: boolean; @@ -759,7 +759,7 @@ function FamilyField({ ) : null} - {describeRemoteChildrenStaying(family.remoteChildren, targetLabel).map((line) => ( + {describeRemoteChildrenStaying(family.remoteChildren, target).map((line) => (

{line}

diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index a8461ae4e..3778eaa72 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -3780,12 +3780,23 @@ function applyEnvironmentOrchestrationEvent( }, ); - case "thread.parent-attachment-set": + case "thread.parent-attachment-set": { + // Taken back by the thread that started it over a link, which moved + // here: a child here now, no longer the other computer's. + const adoptedBy = event.payload.adoptedBy; return updateThreadState(state, event.payload.threadId, (thread) => - (thread.attachedToParent ?? false) === event.payload.attached - ? thread - : { ...thread, attachedToParent: event.payload.attached }, + adoptedBy !== undefined + ? { + ...thread, + attachedToParent: event.payload.attached, + parentThreadId: adoptedBy.parentThreadId, + remoteOrigin: null, + } + : (thread.attachedToParent ?? false) === event.payload.attached + ? thread + : { ...thread, attachedToParent: event.payload.attached }, ); + } case "thread.approval-response-requested": case "thread.user-input-response-requested": diff --git a/apps/web/src/threadMove.test.ts b/apps/web/src/threadMove.test.ts index 6bd895a21..4fb7a8a25 100644 --- a/apps/web/src/threadMove.test.ts +++ b/apps/web/src/threadMove.test.ts @@ -19,6 +19,7 @@ import { describeMoveBatchProgress, describeMoveCandidate, describePendingMove, + describeRemoteChildrenStaying, describeThreadMoveLanding, describeThreadMoveProgress, describeThreadMoveSession, @@ -455,6 +456,35 @@ describe("picking where and with whom", () => { }); }); +describe("describeRemoteChildrenStaying", () => { + const MAC = "environment-mac-mini"; + const children = [ + { label: "Mac mini", title: "Fix tests", environmentId: MAC }, + { label: "Windows PC", title: "Review", environmentId: "environment-windows" }, + { label: "Windows PC", title: "Docs", environmentId: "environment-windows" }, + ]; + + it("says the ones on the computer it moves to become its threads there again, when it takes them", () => { + expect( + describeRemoteChildrenStaying(children, { + label: "Mac mini", + environmentId: MAC, + adoptsChildren: true, + }), + ).toEqual([ + "'Fix tests' on Mac mini becomes its thread there again.", + "2 threads it started on Windows PC stay there. It can't reach them from Mac mini.", + ]); + // An older Mac mini keeps them apart: today's words. + expect( + describeRemoteChildrenStaying(children, { label: "Mac mini", environmentId: MAC }), + ).toEqual([ + "1 thread it started on Mac mini stays there. It can't reach it from Mac mini.", + "2 threads it started on Windows PC stay there. It can't reach them from Mac mini.", + ]); + }); +}); + describe("describeMoveBatchProgress", () => { it("says how a batch goes while it runs, then how it went, naming the ones that didn't move", () => { const running = countMoveBatch(["moved", "waiting", "waiting"]); diff --git a/apps/web/src/threadMove.ts b/apps/web/src/threadMove.ts index 76377188b..8c8f6d603 100644 --- a/apps/web/src/threadMove.ts +++ b/apps/web/src/threadMove.ts @@ -1014,17 +1014,44 @@ export function describeFamilyComing(count: number): string { /** * "2 threads it started on Windows PC stay there. It can't reach them from * Mac mini.", one line per computer, for the threads its agent started on - * other computers. + * other computers. Those on the computer it moves to, when that computer + * takes them back (`adoptsChildren`), become its threads there again + * (docs/design/fleet.md, Part 3f, (g)): "'Fix tests' on Mac mini becomes its + * thread there again." */ export function describeRemoteChildrenStaying( - remoteChildren: ReadonlyArray<{ readonly label: string; readonly title: string }>, - targetLabel: string, + remoteChildren: ReadonlyArray<{ + readonly label: string; + readonly title: string; + readonly environmentId?: string | undefined; + }>, + target: { + readonly label: string; + readonly environmentId: string; + readonly adoptsChildren?: true | undefined; + }, ): string[] { - const byLabel = new Map(); - for (const child of remoteChildren) byLabel.set(child.label, (byLabel.get(child.label) ?? 0) + 1); - return [...byLabel].map(([label, count]) => - count === 1 - ? `1 thread it started on ${label} stays there. It can't reach it from ${targetLabel}.` - : `${count} threads it started on ${label} stay there. It can't reach them from ${targetLabel}.`, + const back = remoteChildren.filter( + (child) => target.adoptsChildren === true && child.environmentId === target.environmentId, ); + const byLabel = new Map(); + for (const child of remoteChildren) { + if (back.includes(child)) continue; + byLabel.set(child.label, (byLabel.get(child.label) ?? 0) + 1); + } + const [only] = back; + return [ + ...(back.length === 0 + ? [] + : [ + back.length === 1 && only !== undefined + ? `'${only.title}' on ${target.label} becomes its thread there again.` + : `${back.length} threads it started on ${target.label} become its threads there again.`, + ]), + ...[...byLabel].map(([label, count]) => + count === 1 + ? `1 thread it started on ${label} stays there. It can't reach it from ${target.label}.` + : `${count} threads it started on ${label} stay there. It can't reach them from ${target.label}.`, + ), + ]; } diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 5cebb6075..74973735e 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1305,7 +1305,7 @@ The transfer (Part 3), the queue and barrier (3b), batches (3c), session carry ( | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | A parent moves with its children | **The family moves together** and arrives as a family: the children are still its children there. | | A parent moves and some children stay | **They become their own threads here**, each with a line saying why. The parent can't reach them from the other computer. | -| A parent has children on another computer | **They stay where they are.** The moved parent can't reach them. Named in the dialog and on arrival. | +| A parent has children on another computer | **They stay where they are.** The moved parent can't reach them. Named in the dialog and on arrival. Moved to that computer, they are its children again there (Nov 18). | | A parent is waiting on answers from its children | "Move when it's done" waits for the answers. "Stop and move now" ends the waiting as Stop does, and says so. | | A child moves and its parent stays | **It stays its parent's child**, as a thread on another computer: the parent can still send to it, read it and stop it over the link. There it is fenced for good, as any thread another computer's agent directs. | | A thread another computer's agent started (or a child that moved there) | **It can move back to that computer, and nowhere else.** At home it becomes a local child of the thread that started it again. | @@ -1316,10 +1316,10 @@ The transfer (Part 3), the queue and barrier (3b), batches (3c), session carry ( These hold for every case below. The first four are the link fence, and a move must never loosen it. -1. **`remoteOrigin` is only ever written by the computer the thread is on, from the link it authenticated.** A manifest can ask for a thread to arrive as its sender's child. It can't supply the link, the environment, or anyone else's. +1. **`remoteOrigin` is only ever written by the computer the thread is on, from the link it authenticated.** A manifest can ask for a thread to arrive as its sender's child. It can't supply the link, the environment, or anyone else's. That computer also clears it in one case only: the thread that asked moves there over that same link and takes the thread back as its child ("Also when the child's computer is the target", below). 2. **A thread with `remoteOrigin` moves only to `remoteOrigin.environmentId`**, and only when that identity is pinned (`environmentPinned`). This is checked in the decider, not the dialog. There is no path from "an agent on A started work on B" to that work running on C. 3. **Every import arrives fenced** (`movedFrom.fenced`, Part 3e). Each thread of a family lifts its own fence with its own message from the user here. A message in the parent doesn't lift a child's. -4. **A peer can't attach a thread under one of this computer's threads.** Lineage is written in two cases only: both threads arrived in the same family from the same link, or this computer's own records already name the incoming thread as that parent's child (coming home). +4. **A peer can't attach a thread under one of this computer's threads.** Lineage is written in three cases only: both threads arrived in the same family from the same link, this computer's own records already name the incoming thread as that parent's child (coming home), or this computer's own records name a thread here as one the incoming thread started over that same link (taken back on arrival, below). 5. **Never on two computers.** The reactors that act for a family (`ChildThreadReactor`, `RemoteChildReactor`) and the room's request chain stop for a thread with `pendingMove` or `move`, as the queue drain and the watcher do since 4a. 6. **Nothing closed is extended.** Waits reuse existing codes with their own words. No new phase, hold kind, outcome, watch event or peer status. @@ -1384,7 +1384,15 @@ A child that isn't in the set, or whose own move failed after the parent's commi - **Open remote requests:** "when done" waits for them as above. "Stop and move now" cancels them through the path Stop already uses (`cancelRequested`, `peer.request.cancel`, `peer.thread.stop`) and settles them here at once. - **`RemoteChildReactor` learns about moves.** It reads only `id`, `title`, `participants`, `childRequests`, `archivedAt` and `deletedAt` today. It now skips a parent with `move` set for watches and for anything that writes to the parent. One exception: `thread.remote-cancels.delivered` joins `FROZEN_THREAD_COMMANDS`, so cancels owed at the freeze still drain. - **A hole this closes.** On a frozen parent the reactor's four commands are refused. It reads a refused settle as "settled meanwhile" and acks the report as not delivered (RemoteChildReactor.ts ~609-619), so the answer is lost. No frozen parent can have remote children today, so it can't happen yet. Skipping frozen parents makes sure it never does. -- **Also when the child's computer is the target.** The parent arrives beside threads it once started there and stays separate from them. Adopting them would turn a thread that is fenced for good into one a message can unfence. The "Moved here" line names them from that computer's own records (threads started over the same link by the thread the move came from): "Its thread 'Fix tests' is already on this computer. It stays separate, so this thread can't reach it." The sender leaves them out of `remoteStayed`, which would otherwise say they "stayed there". +- **Also when the child's computer is the target (Nov 18: taken back on arrival).** Kept apart, such a thread was stranded: fenced for good, pointing at a read-only copy, its reports retried forever, and nobody could direct it. So the parent takes it back as its child there. + - **Who.** A thread both lists name: the sender's `remoteChildren` on the target (`PeerMoveManifest.startedThere`, at most 50, each with the user's pending Wrap up or Reopen), and the target's own records (threads started over this very link by the thread the move came from, not archived, deleted or moved away). The sender sends the list only to a computer that says `PeerDescriptor.moveAdoptsChildren`; an older one keeps them apart, with the line below. Only a thread that lands on its own (no `lineage`, `remoteOrigin` or `adopt`) takes any back; a family's parent does. + - **Checks, per thread, in the decider** (`thread.import`'s `adoptsChildren`, with the link from the transfer's row, never the manifest). Its `remoteOrigin` is this link, names the thread the move came from, and is pinned to the computer the move came from; it is in the same project; it isn't archived, moving or queued to move; it has no attached children; and it asks no more access than the arriving thread has there (its modes as the import writes them, after the link's cap). One that fails stays as it is, never with its access lowered, and the "Moved here" line says why. The import never fails for it. + - **What it becomes.** In the same decision: `remoteOrigin` is cleared, it is the arriving thread's attached child (no parent turn, a fresh attachment epoch), and it carries `adoptedFromLink { environmentId, label, fenced: true }` (`thread.parent-attachment-set` with `adoptedBy`). A newer Wrap up or Reopen from the list stands, as `fromLinkedComputer` decides. Its timeline says what happened. + - **The fence.** It works behind the link fence until a message the user sends in it there lifts it (the moved-thread rule, `turnLiftsMoveFence`). That is Will's call (Nov 18): the user there taking it over is the same proof a moved thread needs. A message in the parent, a `fromThread` send, or a scheduled run doesn't lift it. While fenced it moves only back to `adoptedFromLink.environmentId`. + - **The link lets go first.** Under the transfer lock, before the import, each thread is released (`LinkRequests.releaseThread`): every open request of the link's for it ends cancelled ("The thread that asked moved here."), its queued message is taken back, it is stopped only while the running turn is that request's, and the ledger owes the link nothing more for it (`closeForThread`: reports marked delivered, clean-up and owed stops cleared). After the import lands this runs again for the threads the parent holds. If the import fails, they stay the link's, with those requests ended. + - **Ownership.** Everything the link does to a thread asks first that the thread is still the link's (`ownedThread`): a cancel's clean-up (live and at startup), an ack, send, read, stop and wrap. So the sender's late `peer.request.cancel { stopThread }` stops nothing the user started there since. + - **The answer.** The committed `PeerMoveState.adopted` names them, read from the threads (so a restart between import and answer still says it). `thread.move.complete { adopted }` removes their `remoteChildren` entries from the read-only copy and settles any request still open for them. `RemoteChildReactor` acks a report for a parent that moved away as not delivered, so the target stops offering it. + - **Words.** On the parent: "Its thread 'Fix tests' was already on this computer. It's this thread's again." One kept apart: "Its thread 'Fix tests' is already on this computer. It stays separate because it has more access than this thread has here, so this thread can't reach it." A thread in the target's records but not on the list (an older sender) gets today's line: "Its thread 'Fix tests' is already on this computer. It stays separate, so this thread can't reach it." The sender leaves them out of `remoteStayed`, which would otherwise say they "stayed there". The move dialog says "'Fix tests' on Mac mini becomes its thread there again." to a target that takes them. ### (h) A child, and a thread another computer started @@ -1473,7 +1481,7 @@ Each has a default in this plan. 2. **Children left behind when the parent moves.** Default: they become their own threads here, with a line saying why. The other choice: refuse to move a parent unless every child comes. 3. **A room agent with no match on the other computer.** Default: the room moves without it, shown as having left, named before and after. The other choice: refuse until every agent has a match. 4. **Threads another computer's agent started.** Default: they may move back to that computer and nowhere else. The other choice: keep refusing them entirely. Simpler, but a child that moved out could then never come back. -5. **Children on another computer when the parent moves.** Default: they stay and the parent loses them, named. The other choice: refuse to move such a parent, which keeps most of today's refusal. +5. **Children on another computer when the parent moves.** Default: they stay and the parent loses them, named. The other choice: refuse to move such a parent, which keeps most of today's refusal. (Nov 18: when the parent moves to the computer they are on, it takes them back as its children, fenced until the user there writes in each; see (g).) 6. **Tools for a moved family.** Default: each thread needs its own message from the user to get its tools back. The other choice: a message in the parent also unfences the children that came with it. More convenient, and looser than the rule the security fix just set. ### Build order @@ -1513,7 +1521,6 @@ Each waits for the security scan before it merges. - Keeping children as the moved parent's children when they stay behind (needs the reverse link's permission). - Handing a child on another computer over to the parent's new computer. -- Adopting threads already on the target when their parent arrives. - Moving the lead chat. - A message in the parent unfencing its children (call 6). diff --git a/packages/contracts/src/moves.ts b/packages/contracts/src/moves.ts index bb554667b..ddc5a60ef 100644 --- a/packages/contracts/src/moves.ts +++ b/packages/contracts/src/moves.ts @@ -128,6 +128,12 @@ export const ThreadMoveTargetPreview = Schema.Struct({ * Windows PC to move it on its own."). Absent: it can. */ aloneRefusal: Schema.optional(TrimmedNonEmptyString), + /** + * A thread that started threads on this computer: they become its threads + * there again (ThreadMovePreview.family.remoteChildren with this + * `environmentId`). Absent: they stay apart there, as an older server keeps them. + */ + adoptsChildren: Schema.optional(Schema.Literal(true)), }); export type ThreadMoveTargetPreview = typeof ThreadMoveTargetPreview.Type; @@ -199,7 +205,12 @@ export const ThreadMovePreview = Schema.Struct({ }), ), remoteChildren: Schema.Array( - Schema.Struct({ label: TrimmedNonEmptyString, title: TrimmedNonEmptyString }), + Schema.Struct({ + label: TrimmedNonEmptyString, + title: TrimmedNonEmptyString, + /** The computer it is on. Absent from an older server. */ + environmentId: Schema.optional(EnvironmentId), + }), ), }), ), diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 0f3acb095..b011b138b 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -665,8 +665,11 @@ export type ThreadMessageOrigin = typeof ThreadMessageOrigin.Type; /** * A thread another computer's agent started here over a computer link * (docs/design/fleet.md, "Fence"): which link asked, and the asking thread on - * that computer. Set once, at creation, and only by the server's link - * handler; such a thread gets no Threadlines agent tools. + * that computer. Set at creation, and only by the server's link handler; such + * a thread gets no Threadlines agent tools. Cleared in one case only, by this + * computer: the asking thread moved here over that same link and took the + * thread back as its own child (ThreadAdoptedFromLink, docs/design/fleet.md, + * Part 3f, (g)). */ export const ThreadRemoteOrigin = Schema.Struct({ /** The asking computer's device id on this server (its link). */ @@ -684,6 +687,22 @@ export const ThreadRemoteOrigin = Schema.Struct({ }); export type ThreadRemoteOrigin = typeof ThreadRemoteOrigin.Type; +/** + * A thread another computer's agent started here that became a child here + * when that agent's thread moved here over the same link (docs/design/ + * fleet.md, Part 3f, (g), "Also when the child's computer is the target"): + * the computer it was started from. `fenced`: it still works behind the link + * fence (no Threadlines tools, and it moves only back to `environmentId`) + * until a message the user sends here starts a turn in it. Written only by + * this computer, in the decision that imports the parent. + */ +export const ThreadAdoptedFromLink = Schema.Struct({ + environmentId: EnvironmentId, + label: TrimmedNonEmptyString, + fenced: Schema.Boolean, +}); +export type ThreadAdoptedFromLink = typeof ThreadAdoptedFromLink.Type; + /** * A thread a scheduled task's run started (docs/design/fleet.md, Part 6): * "Scheduled · " on its inbox row. Set once, at creation, and only by @@ -890,6 +909,12 @@ export const ThreadMoveTakes = Schema.Struct({ * there, and a thread another computer's agent started, going back home. */ linkLineage: Schema.optional(Schema.Literal(true)), + /** + * A thread that started threads on that computer (docs/design/fleet.md, + * Part 3f, (g)): those threads become its children there again + * (PeerMoveManifest.startedThere). + */ + adoptsChildren: Schema.optional(Schema.Literal(true)), }); export type ThreadMoveTakes = typeof ThreadMoveTakes.Type; @@ -3044,6 +3069,8 @@ export const OrchestrationThread = Schema.Struct({ ), /** See OrchestrationThreadShell.remoteOrigin. */ remoteOrigin: Schema.optional(Schema.NullOr(ThreadRemoteOrigin)), + /** See OrchestrationThreadShell.adoptedFromLink. */ + adoptedFromLink: Schema.optional(Schema.NullOr(ThreadAdoptedFromLink)), /** See OrchestrationThreadShell.scheduledRun. */ scheduledRun: Schema.optional(Schema.NullOr(ThreadScheduledRun)), /** See OrchestrationThreadShell.worktreeOrigin. */ @@ -3306,6 +3333,12 @@ export const OrchestrationThreadShell = Schema.Struct({ * by on ". Absent or null: started here. */ remoteOrigin: Schema.optional(Schema.NullOr(ThreadRemoteOrigin)), + /** + * Started over a link, then taken back as a child here by the thread that + * started it, when that thread moved here (ThreadAdoptedFromLink). Absent + * or null: neither. + */ + adoptedFromLink: Schema.optional(Schema.NullOr(ThreadAdoptedFromLink)), /** Moving, or moved, to a linked computer: see OrchestrationThreadMove. Absent or null: neither. */ move: Schema.optional(Schema.NullOr(OrchestrationThreadMove)), /** A move waiting for the thread to be free: see ThreadPendingMove. Absent or null: none. */ @@ -5464,6 +5497,12 @@ const ThreadMoveCompleteCommand = Schema.Struct({ * child on that computer. Absent: it is a thread of its own there. */ keptParent: Schema.optional(Schema.Literal(true)), + /** + * Threads its agent started on that computer that became its children + * there (PeerMoveState.adopted, docs/design/fleet.md, Part 3f, (g)): the + * copy here stops keeping them as children on that computer. Absent: none. + */ + adopted: Schema.optional(Schema.Array(ThreadId)), createdAt: IsoDateTime, }); @@ -5645,6 +5684,27 @@ const ThreadImportCommand = Schema.Struct({ ), }), ), + /** + * Threads here that the moving thread's agent started over this link while + * it was on the computer it came from (docs/design/fleet.md, Part 3f, (g), + * "Also when the child's computer is the target"), each with the user's + * Wrap up or Reopen given there that this computer may not have yet. Each + * that still qualifies becomes the arriving thread's child, fenced until + * the user here sends it a message; one that doesn't stays as it is, and + * the "Moved here" line says why. `linkDeviceId` is the link the move came + * over, from the transfer's own record; only a top-level import has it. + */ + adoptsChildren: Schema.optional( + Schema.Struct({ + linkDeviceId: TrimmedNonEmptyString, + children: Schema.Array( + Schema.Struct({ + threadId: ThreadId, + override: Schema.optional(OrchestrationThreadDoneOverride), + }), + ), + }), + ), /** * What the "Moved here" line says came along (`brought`) and didn't * (`left`), in plain words, and the message Threadlines writes for the @@ -6420,6 +6480,19 @@ export const ThreadParentAttachmentSetPayload = Schema.Struct({ attached: Schema.Boolean, attachmentEpoch: NonNegativeInt, at: IsoDateTime, + /** + * A thread another computer's agent started here becomes the child of + * that agent's thread, which moved here (ThreadAdoptedFromLink): its + * parent is `parentThreadId` (no parent turn), it is no longer that + * computer's (`remoteOrigin` goes), and it works fenced until the user + * here sends it a message. Absent: only the attachment changes. + */ + adoptedBy: Schema.optional( + Schema.Struct({ + parentThreadId: ThreadId, + fromLink: ThreadAdoptedFromLink, + }), + ), }); export const ThreadRoomContextRecordedPayload = Schema.Struct({ diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts index 48ab86d98..dc39b7d6d 100644 --- a/packages/contracts/src/peerRpc.ts +++ b/packages/contracts/src/peerRpc.ts @@ -286,6 +286,14 @@ export const PeerDescriptor = Schema.Struct({ * ever sent to it. */ moveLinkLineage: Schema.optional(Schema.Boolean), + /** + * Takes back the threads a moving thread's agent started here over this + * link as that thread's children (docs/design/fleet.md, Part 3f, (g)): + * PeerMoveManifest's `startedThere`, and `adopted` on the committed answer. + * Absent: an older server, which keeps them apart, so it is never sent the + * list. + */ + moveAdoptsChildren: 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. @@ -738,6 +746,24 @@ export const PeerMoveFamily = Schema.Struct({ }); export type PeerMoveFamily = typeof PeerMoveFamily.Type; +/** At most this many threads a manifest names as started on the receiving computer. */ +export const PEER_MOVE_MAX_STARTED_THERE = 50; + +/** + * A thread the moving thread's agent started on the receiving computer + * (docs/design/fleet.md, Part 3f, (g), "Also when the child's computer is + * the target"), by the receiving computer's own id, as the sending + * computer's records hold it (RemoteChildThread), with the user's Wrap up or + * Reopen given on the sending computer. Only to a computer that says + * `moveAdoptsChildren`. The receiving computer takes back only the threads + * its own records also name as started over this link by this thread. + */ +export const PeerMoveStartedThere = Schema.Struct({ + threadId: ThreadId, + override: Schema.optional(OrchestrationThreadDoneOverride), +}); +export type PeerMoveStartedThere = typeof PeerMoveStartedThere.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 @@ -795,6 +821,8 @@ export const PeerMoveScratchManifest = Schema.Struct({ family: Schema.optional(PeerMoveFamily), /** It moves across the link its work came over: see PeerMoveLinkLineage. */ linkLineage: Schema.optional(PeerMoveLinkLineage), + /** The threads its agent started there: see PeerMoveStartedThere. */ + startedThere: Schema.optional(Schema.Array(PeerMoveStartedThere)), }); export type PeerMoveScratchManifest = typeof PeerMoveScratchManifest.Type; @@ -846,6 +874,8 @@ export const PeerMoveGitManifest = Schema.Struct({ family: Schema.optional(PeerMoveFamily), /** It moves across the link its work came over: see PeerMoveLinkLineage. */ linkLineage: Schema.optional(PeerMoveLinkLineage), + /** The threads its agent started there: see PeerMoveStartedThere. */ + startedThere: Schema.optional(Schema.Array(PeerMoveStartedThere)), }); export type PeerMoveGitManifest = typeof PeerMoveGitManifest.Type; @@ -930,6 +960,13 @@ export const PeerMoveState = Schema.Struct({ * own here, or an older server. */ keptParent: Schema.optional(Schema.Literal(true)), + /** + * `committed`: the threads named in `startedThere` that became its + * children here, by their ids here (the calling computer's + * RemoteChildThread ids). Read from this computer's threads, so a retried + * call answers the same. Absent: none, or an older server. + */ + adopted: Schema.optional(Schema.Array(ThreadId)), }); export type PeerMoveState = typeof PeerMoveState.Type; diff --git a/packages/shared/src/threadMoveProjection.ts b/packages/shared/src/threadMoveProjection.ts index 89f48950b..5e7880164 100644 --- a/packages/shared/src/threadMoveProjection.ts +++ b/packages/shared/src/threadMoveProjection.ts @@ -21,6 +21,7 @@ import type { OrchestrationThreadMove, ThreadMoveOutcome, ThreadMoveOutcomeReason, + ThreadAdoptedFromLink, ThreadMovedFrom, ThreadPendingMove, } from "@threadlines/contracts"; @@ -241,6 +242,18 @@ export function movedFromAfter( } as T; } +/** + * Where an adopted thread was started from (ThreadAdoptedFromLink), after a + * message the user sent here lifted the fence (`liftsMoveFence`, the same + * event that lifts a moved thread's). The same object when it isn't fenced. + */ +export function adoptedFromLinkAfterLift( + adopted: T, +): T { + if (adopted === null || adopted === undefined || !adopted.fenced) return adopted; + return { ...adopted, fenced: false } as T; +} + /** A thread's pull request switches, as a move carries them (own switch, then each linked one). */ export interface MovedPullRequestSwitches { readonly autoFix: boolean; From 14be583207c417e54534933ad48da3bcbb6031c5 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:38:26 -0500 Subject: [PATCH 2/3] fix(server): a link can't act on a thread its asker took back, and keeps what stays apart Review fixes for taking a link's threads back on arrival: - The decider now guards what a link asks for: a stop, Wrap up or answer's record names the link (byLink) and is refused unless the thread is still that link's, and a link's queued request is taken back instead of run once it isn't. The LinkRequests read before it can be stale. - One shared check (adoptionRefusal) decides which threads qualify. LinkMoves asks it before releasing anything, with the modes the import will write, so a thread that stays apart keeps its requests. Archived ones the manifest names now say why they stay apart. - Release stops the turn the link's request started, found from the thread's turn starts (the ledger has no turn id while it runs), and never a turn the user started since. - After the import lands, the adopted threads are released again, so a send that arrived in between ends and its message is taken back. --- apps/server/src/links/LinkMoves.test.ts | 85 +++++++++-- apps/server/src/links/LinkMoves.ts | 132 +++++++++++----- apps/server/src/links/LinkRequests.test.ts | 141 +++++++++++++++++- apps/server/src/links/LinkRequests.ts | 87 +++++++---- .../src/orchestration/childThreadDecisions.ts | 5 + .../decider.childThreads.test.ts | 115 ++++++++++++++ apps/server/src/orchestration/decider.ts | 30 +++- apps/server/src/orchestration/linkFence.ts | 15 ++ .../src/orchestration/threadMoveDecisions.ts | 116 +++++++++----- .../persistence/Layers/ProjectionThreads.ts | 23 +++ .../persistence/Services/ProjectionThreads.ts | 5 + docs/design/fleet.md | 6 +- packages/contracts/src/orchestration.ts | 12 ++ 13 files changed, 635 insertions(+), 137 deletions(-) diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index 1fe7e512c..53bbe56dc 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -186,10 +186,9 @@ interface CarryRecord { readonly threadsHere?: ReadonlyArray<{ readonly threadId: ThreadId } & Record>; /** * Threads this link gave up (LinkRequests.releaseThread), each with how - * many commands were dispatched by then, and the ones closed for it after. + * many commands were dispatched by then. */ readonly released?: Array<{ readonly threadId: ThreadId; readonly dispatchedBefore: number }>; - readonly closed?: Array; } /** The services LinkMoves leans on, with this computer's git real and the rest faked. */ @@ -239,8 +238,6 @@ function testLayer( Effect.sync( () => void carry.released?.push({ threadId, dispatchedBefore: dispatched.length }), ), - closeThread: (_deviceId, threadId) => - Effect.sync(() => void carry.closed?.push(threadId)), // An instance this computer doesn't have ("gone") is refused. resolveAgentFor: (input) => Effect.succeed( @@ -300,6 +297,14 @@ function testLayer( : [], ), ), + listAttachedChildIds: ({ parentThreadId }) => + Effect.succeed( + (carry.threadsHere ?? []).flatMap((row) => + row.parentThreadId === parentThreadId && row.attachedToParent === 1 + ? [row.threadId] + : [], + ), + ), listIdsByRemoteLink: ({ linkDeviceId }) => Effect.succeed( (carry.threadsHere ?? []).flatMap((row) => @@ -2293,11 +2298,19 @@ describe("a thread moving across its link (Part 3f, (h))", () => { describe("a parent taking back the threads it started here (Part 3f, (g))", () => { /** A thread the link started here for the moving thread (`thread-a` there). */ - const startedHere = (threadId: string, title: string) => ({ + const startedHere = (threadId: string, title: string, extra: Record = {}) => ({ threadId: ThreadId.make(threadId), title, + projectId: ProjectId.make("project-b"), + runtimeMode: "approval-required", + interactionMode: "default", + move: null, + pendingMove: null, + parentThreadId: null, + attachedToParent: 0, deletedAt: null, archivedAt: null, + ...extra, remoteOrigin: { linkDeviceId: "device-windows", environmentId: WINDOWS, @@ -2316,11 +2329,15 @@ describe("a thread moving across its link (Part 3f, (h))", () => { const arriving = ( repos: ReturnType, dispatched: OrchestrationCommand[], - carry: Pick, + carry: Pick, linkLineage?: MoveExportInput["linkLineage"], + listed: ReadonlyArray<{ readonly threadId: ThreadId }> = startedThere, ) => Effect.gen(function* () { - const packed = yield* pack(repos, null, undefined, { startedThere, linkLineage }); + const packed = yield* pack(repos, null, undefined, { + startedThere: [...listed], + linkLineage, + }); const state = yield* deliver(packed.manifest, packed.payload); // Asked again (a restart, a lost answer): read from the threads, the same. const again = yield* (yield* LinkMoves).status(link("allowed"), { transferId: TRANSFER }); @@ -2345,9 +2362,8 @@ describe("a thread moving across its link (Part 3f, (h))", () => { const repos = makeRepos(); const dispatched: OrchestrationCommand[] = []; const released: NonNullable = []; - const closed: ThreadId[] = []; return Effect.gen(function* () { - const { state, again } = yield* arriving(repos, dispatched, { released, closed }); + const { state, again } = yield* arriving(repos, dispatched, { released }); assert.equal(state.status, "committed"); const imported = importOf(dispatched); assert.deepEqual(imported.adoptsChildren, { @@ -2361,13 +2377,13 @@ describe("a thread moving across its link (Part 3f, (h))", () => { "Its thread 'Only here' is already on this computer. It stays separate, so this thread can't reach it.", ], ); - // The link let go of it before the import, and owes it nothing once it landed. + // The link let go of it before the import, and again once it landed. assert.deepEqual( released.map((entry) => entry.threadId), - ["thread-both"], + ["thread-both", "thread-both"], ); assert.isAtMost(released[0]!.dispatchedBefore, dispatched.indexOf(imported)); - assert.include(closed, ThreadId.make("thread-both")); + assert.isAbove(released[1]!.dispatchedBefore, dispatched.indexOf(imported)); assert.deepEqual(state.adopted, [ThreadId.make("thread-both")]); assert.deepEqual(again.adopted, [ThreadId.make("thread-both")]); }); @@ -2381,7 +2397,7 @@ describe("a thread moving across its link (Part 3f, (h))", () => { const { state } = yield* arriving( repos, dispatched, - { released, closed: [] }, + { released }, { remoteParent: { threadId: ThreadId.make("thread-parent-on-windows"), title: "Ship" } }, ); assert.equal(state.status, "committed"); @@ -2390,6 +2406,49 @@ describe("a thread moving across its link (Part 3f, (h))", () => { assert.isUndefined(state.adopted); }); }); + + it.live("one on its list that can't be taken back keeps its requests, and says why", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + const released: NonNullable = []; + const listed = ["thread-full-access", "thread-archived", "thread-moving"].map((id) => ({ + threadId: ThreadId.make(id), + })); + return Effect.gen(function* () { + const { state } = yield* arriving( + repos, + dispatched, + { + released, + threadsHere: [ + // More access than the parent gets here (its modes after the link's cap). + startedHere("thread-full-access", "Full access", { runtimeMode: "full-access" }), + startedHere("thread-archived", "Archived", { + archivedAt: "2026-11-17T10:00:00.000Z", + }), + startedHere("thread-moving", "Moving", { pendingMove: { requestId: "r" } }), + ], + }, + undefined, + listed, + ); + assert.equal(state.status, "committed"); + const imported = importOf(dispatched); + assert.isUndefined(imported.adoptsChildren); + // Never released: what its link asked of it still stands. + assert.deepEqual(released, []); + const line = (title: string, why: string) => + `Its thread '${title}' is already on this computer. It stays separate because ${why}, so this thread can't reach it.`; + assert.includeMembers( + [...(imported.arrival?.left ?? [])], + [ + line("Full access", "it has more access than this thread has here"), + line("Archived", "it's archived"), + line("Moving", "it's moving"), + ], + ); + }); + }); }); it("refuses a manifest naming both a parent and a home, itself, or a family too", () => { diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index d90c4f2f8..1dececacc 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -114,8 +114,16 @@ import { OrchestrationEngineService } from "../orchestration/Services/Orchestrat import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ComputerLinkRepository } from "./ComputerLinkRepository.ts"; import { linkMoveCopyThreadId, linkMoveKey, linkMoveThreadId } from "../moves/linkMoveIds.ts"; -import { awaitsLoneMoveAnswer } from "../orchestration/threadMoveDecisions.ts"; -import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts"; +import { + type AdoptionArrival, + adoptionApartWords, + adoptionRefusal, + awaitsLoneMoveAnswer, +} from "../orchestration/threadMoveDecisions.ts"; +import { + type ProjectionThread, + ProjectionThreadRepository, +} from "../persistence/Services/ProjectionThreads.ts"; import { discardSessionFiles, releaseSessionFiles } from "../provider/nativeSession.ts"; import { ProviderService } from "../provider/Services/ProviderService.ts"; import { RepositoryIdentityResolver } from "../project/Services/RepositoryIdentityResolver.ts"; @@ -1402,7 +1410,7 @@ const make = Effect.gen(function* () { ); } } - yield* closeAdopted(row); + yield* releaseAdopted(row); return yield* moves.settle({ linkDeviceId: row.linkDeviceId, transferId: row.transferId, @@ -2440,12 +2448,13 @@ const make = Effect.gen(function* () { /** * The threads its agent started on this computer while it was on the one * it came from (docs/design/fleet.md, Part 3f, (g), "Also when the child's - * computer is the target"). Read from this computer's own records alone: - * threads started over this very link by the thread the move came from, - * still here (not archived, deleted or moved away). Those the manifest - * also names (`startedThere`) may become the arriving thread's children; - * the rest stay apart, and it can't reach them. A failed read names none - * rather than failing the move. + * computer is the target"), as their rows read. Read from this computer's + * own records alone: threads started over this very link by the thread the + * move came from, still here (not deleted or moved away; archived ones + * too, so one the manifest names can say why it stays apart). Those the + * manifest also names (`startedThere`) may become the arriving thread's + * children; the rest stay apart, and it can't reach them. A failed read + * names none rather than failing the move. */ const threadsStartedHere = (row: LinkMoveRow) => Effect.gen(function* () { @@ -2453,38 +2462,69 @@ const make = Effect.gen(function* () { const found = yield* Effect.forEach(ids, (threadId) => threadRows.getById({ threadId }), { concurrency: 8, }); - return found.flatMap( - (entry): Array<{ readonly threadId: ThreadId; readonly title: string }> => { - const thread = Option.getOrUndefined(entry); - return thread !== undefined && - thread.deletedAt === null && - thread.archivedAt === null && - thread.move?.movedAway === undefined && - thread.remoteOrigin?.linkDeviceId === row.linkDeviceId && - thread.remoteOrigin.threadId === row.manifest.source.threadId - ? [{ threadId: thread.threadId, title: thread.title }] - : []; - }, - ); + return found.flatMap((entry): Array => { + const thread = Option.getOrUndefined(entry); + return thread !== undefined && + thread.deletedAt === null && + thread.move?.movedAway === undefined && + thread.remoteOrigin?.linkDeviceId === row.linkDeviceId && + thread.remoteOrigin.threadId === row.manifest.source.threadId + ? [thread] + : []; + }); + }).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + + /** + * Which of the threads it started here the arriving thread may take back + * (the same check the decider makes again, adoptionRefusal), and the + * "Moved here" words for the ones the manifest names that stay apart. + * Only these are released: a thread that stays apart keeps what its link + * asked of it. + */ + const adoptionCandidates = (listed: ReadonlyArray, arrival: AdoptionArrival) => + Effect.gen(function* () { + const adoptable: Array = []; + const apart: Array = []; + for (const thread of listed) { + const children = yield* threadRows.listAttachedChildIds({ + parentThreadId: thread.threadId, + }); + const why = adoptionRefusal( + { + remoteOrigin: thread.remoteOrigin ?? null, + projectId: thread.projectId, + archivedAt: thread.archivedAt, + moving: (thread.move ?? null) !== null || (thread.pendingMove ?? null) !== null, + inFamily: + ((thread.parentThreadId ?? null) !== null && (thread.attachedToParent ?? 0) > 0) || + children.length > 0, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + }, + arrival, + ); + if (why === null) adoptable.push(thread); + else apart.push(adoptionApartWords(thread.title, why)); + } + return { adoptable, apart }; }).pipe( - Effect.orElseSucceed( - (): ReadonlyArray<{ readonly threadId: ThreadId; readonly title: string }> => [], - ), + Effect.mapError(() => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` })), ); /** * After the thread landed: the threads it took back as its children here - * owe the link nothing more (LinkRequests.closeThread), whatever arrived - * between their release and the import. Read from the projection, so a - * restart in between closes them too. + * are let go by the link again (LinkRequests.releaseThread), so a request + * that arrived between their release and the import ends too, and its + * message is taken back. Read from the projection, so a restart in between + * finishes it. */ - const closeAdopted = (row: LinkMoveRow) => + const releaseAdopted = (row: LinkMoveRow) => Effect.gen(function* () { const adopted = yield* threadRows.listAdoptedChildIds({ parentThreadId: row.threadId }); - for (const threadId of adopted) yield* requests.closeThread(row.linkDeviceId, threadId); + for (const threadId of adopted) yield* requests.releaseThread(row.linkDeviceId, threadId); }).pipe( Effect.catch((error) => - Effect.logWarning("a moved thread's adopted threads couldn't be closed for their link", { + Effect.logWarning("a moved thread's adopted threads couldn't be released by their link", { threadId: row.threadId, detail: String(error), }), @@ -2693,13 +2733,15 @@ 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 startedHere = yield* threadsStartedHere(row); + // Archived ones aren't named as here, unless the manifest names them (below). + const liveHere = startedHere.filter((thread) => thread.archivedAt === null); const familyLeft = family === null ? [] : family.left( fromLabel, lineage?.left ?? null, - new Set(startedHere.map((entry) => entry.title)), + new Set(liveHere.map((entry) => entry.title)), ); // Across the link its work came over (Part 3f, (h)): from this link alone. const across = yield* linkLanding( @@ -2711,8 +2753,10 @@ const make = Effect.gen(function* () { if (across.left !== undefined) familyLeft.push(across.left); // The threads it started here that may be its children again (Part 3f, // (g)): named by both the manifest and this computer's own records, - // and only for a thread that lands on its own here. The decider checks - // each again and words the outcome; the others stay apart, named here. + // only for a thread that lands on its own here, and only those that + // pass the check the decider makes again (its modes as the import + // writes them). One the manifest names that doesn't pass says why; + // the others stay apart, named here. const askedBack = new Map( (row.manifest.startedThere ?? []).map((entry) => [entry.threadId as string, entry]), ); @@ -2720,16 +2764,22 @@ const make = Effect.gen(function* () { lineage?.lineage === undefined && across.remoteOrigin === undefined && across.adopt === undefined; - const adoptable = topLevel - ? startedHere.filter((entry) => askedBack.has(entry.threadId)) - : []; - const adoptableIds = new Set(adoptable.map((entry) => entry.threadId)); + const listed = topLevel ? startedHere.filter((entry) => askedBack.has(entry.threadId)) : []; + const listedIds = new Set(listed.map((entry) => entry.threadId)); + const { adoptable, apart } = yield* adoptionCandidates(listed, { + linkDeviceId: row.linkDeviceId, + sourceThreadId: row.manifest.source.threadId, + fromEnvironmentId: authority.pinnedEnvironmentId ?? row.manifest.source.environmentId, + fromPinned: authority.pinnedEnvironmentId !== null, + projectId: land.project.id, + runtimeMode: capped.runtimeMode, + interactionMode: capped.interactionMode, + }); const startedHereLine = startedHereWords( - startedHere - .filter((entry) => !adoptableIds.has(entry.threadId)) - .map((entry) => entry.title), + liveHere.filter((entry) => !listedIds.has(entry.threadId)).map((entry) => entry.title), ); if (startedHereLine !== null) familyLeft.push(startedHereLine); + familyLeft.push(...apart); // The "Moved here" line's room words first, then its family's, then // what the thread had going. const arrival = diff --git a/apps/server/src/links/LinkRequests.test.ts b/apps/server/src/links/LinkRequests.test.ts index f8738e22b..c2fb9fae2 100644 --- a/apps/server/src/links/LinkRequests.test.ts +++ b/apps/server/src/links/LinkRequests.test.ts @@ -349,15 +349,18 @@ const stopsFor = (events: ReadonlyArray, threadId: ThreadId) /** * The thread that asked (PARENT on Windows PC) moves here and takes the * link's thread back as its child (docs/design/fleet.md, Part 3f, (g)): - * released by the link first, then imported, as LinkMoves does it. + * released by the link first, then imported, as LinkMoves does it + * (`release: false` imports only, as if the release had run before + * something new arrived). */ const takenBack = ( computer: Computer, service: Effect.Success>, threadId: ThreadId, + options: { readonly release?: boolean } = {}, ) => Effect.gen(function* () { - yield* service.releaseThread(DEVICE, threadId); + if (options.release !== false) yield* service.releaseThread(DEVICE, threadId); yield* computer.engine.dispatch({ type: "thread.import", commandId: CommandId.make("import-parent"), @@ -387,11 +390,11 @@ const takenBack = ( }); /** The user here starts a turn in the thread, and its agent is at work on it. */ -const userTurnRunning = (computer: Computer, threadId: ThreadId) => +const userTurnRunning = (computer: Computer, threadId: ThreadId, turnId = "user-turn") => Effect.gen(function* () { yield* computer.engine.dispatch({ type: "thread.session.set", - commandId: CommandId.make("user-turn-running"), + commandId: CommandId.make(`running-${turnId}`), threadId, session: { threadId, @@ -399,7 +402,7 @@ const userTurnRunning = (computer: Computer, threadId: ThreadId) => providerName: "codex", providerInstanceId: ProviderInstanceId.make("codex"), runtimeMode: "auto", - activeTurnId: TurnId.make("user-turn"), + activeTurnId: TurnId.make(turnId), lastError: null, updatedAt: AT, }, @@ -407,6 +410,17 @@ const userTurnRunning = (computer: Computer, threadId: ThreadId) => }); }); +/** A service whose reads of `threadId` return `stale`: it read the thread just before it changed. */ +const bootReadingStale = (computer: Computer, threadId: ThreadId, stale: unknown) => + computer.boot({ + snapshots: { + getThreadDetailById: (id: ThreadId) => + id === threadId + ? Effect.succeed(Option.some(stale as never)) + : computer.snapshots.getThreadDetailById(id), + }, + }); + it.layer(NodeServices.layer)("LinkRequests", (it) => { it.effect("records a start once: a retry gets the same thread and starts nothing more", () => Effect.gen(function* () { @@ -1596,6 +1610,123 @@ it.layer(NodeServices.layer)("LinkRequests", (it) => { }), ); + it.effect( + "a stop, Wrap up or ack the link read just before the take-back does nothing to the thread", + () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { service, threadId } = yield* startedChild(computer, "request-1"); + // An answer from the turn now running, which the asker hasn't acked yet. + yield* service.send(link(), { + requestId: ChildRequestId.make("send-1"), + threadId, + text: "Add the security fixes too.", + }); + yield* userTurnRunning(computer, threadId, "turn-send"); + const child = (yield* computer.thread(threadId))!; + yield* service.onTurnEnd({ + child: { + ...child, + messages: [ + ...child.messages, + { + id: MessageId.make("answer"), + role: "assistant", + text: "Added the two security fixes.", + turnId: TurnId.make("turn-send"), + streaming: false, + createdAt: AT, + updatedAt: AT, + }, + ], + }, + end: { turnId: TurnId.make("turn-send"), outcome: "completed" }, + pendingMessageId: linkMessageId(DEVICE, "send-1"), + createdAt: AT, + }); + const stale = yield* computer.thread(threadId); + yield* takenBack(computer, service, threadId, { release: false }); + const before = stopsFor(yield* computer.events, threadId); + + const late = yield* bootReadingStale(computer, threadId, stale); + yield* late.stopThread(link(), threadId); + yield* late.wrapThread(link(), { threadId, override: { state: "done", at: AT } }); + yield* late.ack(link(), { reportId: "send-1:report", delivered: true }); + assert.equal(stopsFor(yield* computer.events, threadId), before); + const after = (yield* computer.thread(threadId))!; + assert.isNull(after.doneOverride); + assert.isNull(after.handedBackTurnId); + }), + ); + + it.effect( + "release stops the turn the link's request started, and never one the user started after it", + () => + Effect.gen(function* () { + // Its own turn running: the ledger has no turn id for it yet. + const asked = yield* makeComputer(); + yield* asked.addLink(DEVICE, "allowed", "active", WINDOWS); + const first = yield* startedChild(asked, "request-1"); + yield* userTurnRunning(asked, first.threadId, "turn-asked"); + assert.isNull((yield* asked.request("request-1")).turnId); + const before = stopsFor(yield* asked.events, first.threadId); + yield* first.service.releaseThread(DEVICE, first.threadId); + assert.equal(stopsFor(yield* asked.events, first.threadId), before + 1); + + // The user started a turn here since: that one runs on. + const mine = yield* makeComputer(); + yield* mine.addLink(DEVICE, "allowed", "active", WINDOWS); + const second = yield* startedChild(mine, "request-1"); + yield* mine.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("user-turn"), + threadId: second.threadId, + message: { + messageId: MessageId.make("m-user"), + role: "user", + text: "Also check the docs.", + attachments: [], + }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: AT, + }); + yield* userTurnRunning(mine, second.threadId, "turn-user"); + const mineBefore = stopsFor(yield* mine.events, second.threadId); + yield* second.service.releaseThread(DEVICE, second.threadId); + assert.equal(stopsFor(yield* mine.events, second.threadId), mineBefore); + assert.equal((yield* mine.request("request-1")).status, "cancelled"); + }), + ); + + it.effect( + "a send that landed between the release and the take-back ends, and its message is taken back", + () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { service, threadId } = yield* startedChild(computer, "request-1"); + yield* service.releaseThread(DEVICE, threadId); + const sent = yield* service.send(link(), { + requestId: ChildRequestId.make("send-late"), + threadId, + text: "One more thing.", + }); + assert.equal(sent.status, "queued"); + yield* takenBack(computer, service, threadId, { release: false }); + // Released again once it landed, as LinkMoves does. + yield* service.releaseThread(DEVICE, threadId); + assert.equal((yield* computer.request("send-late")).status, "cancelled"); + const child = (yield* computer.thread(threadId))!; + assert.isFalse( + (child.queuedFollowUps ?? []).some( + (queued) => queued.messageId === linkMessageId(DEVICE, "send-late"), + ), + ); + }), + ); + it.effect("a thread its asker took back answers the link as not its own", () => Effect.gen(function* () { const computer = yield* makeComputer(); diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index a7c6d0a4b..2fba97480 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -261,8 +261,6 @@ export interface LinkRequestsShape { deviceId: string, threadId: ThreadId, ) => Effect.Effect; - /** Every report about the thread counts as delivered: see LinkRequestRepository.closeForThread. */ - readonly closeThread: (deviceId: string, threadId: ThreadId) => Effect.Effect; readonly onTurnEnd: RemoteRequestTurnEndsShape["onTurnEnd"]; /** See RemoteRequestGate. */ readonly messageVerdict: RemoteRequestGateShape["messageVerdict"]; @@ -1244,25 +1242,43 @@ const make = Effect.gen(function* () { /** * Stops a link's thread if it is still working; fails if the stop wasn't * recorded. `retry` makes it a new stop (the first one, already recorded, - * didn't take), not a replay of the first. + * didn't take), not a replay of the first. The stop names the link + * (`byLink`), so the decider refuses it when the thread stopped being the + * link's after it was read here (its asker took it back, Part 3f, (g)): + * that refusal is an answer (`not_yours`), not a failure. `asLink: false` + * is this computer's own stop, of a turn it found the link's request + * started. */ - const stopIfWorking = (deviceId: string, thread: OrchestrationThread, retry?: string) => + const stopIfWorking = ( + deviceId: string, + thread: OrchestrationThread, + retry?: string, + options: { readonly asLink?: boolean } = {}, + ) => Effect.gen(function* () { if (!isWorking(thread)) return "not_running" as const; - yield* mustDispatch( - { - type: "thread.session.stop", - commandId: CommandId.make( - `server:link-stop:${deviceId}:${thread.id}:${turnKeyOf(thread)}${ - retry === undefined ? "" : `:retry:${retry}` - }`, - ), - threadId: thread.id, - createdAt: yield* nowIso, - }, - "stop that thread", - ); - return "stopped" as const; + const command: OrchestrationCommand = { + type: "thread.session.stop", + commandId: CommandId.make( + `server:link-stop:${deviceId}:${thread.id}:${turnKeyOf(thread)}${ + retry === undefined ? "" : `:retry:${retry}` + }`, + ), + threadId: thread.id, + ...(options.asLink === false ? {} : { byLink: deviceId }), + createdAt: yield* nowIso, + }; + if (options.asLink === false) { + yield* mustDispatch(command, "stop that thread"); + return "stopped" as const; + } + const stopped = yield* dispatchUnlessRefused(command, "stop that thread"); + if (stopped === "ok") return "stopped" as const; + // Refused: either no longer the link's, or for a reason a retry won't change. + const now = yield* readThreadOrFail(thread.id); + return now !== undefined && now.remoteOrigin?.linkDeviceId === deviceId + ? ("not_running" as const) + : ("not_yours" as const); }); /** @@ -1279,8 +1295,9 @@ const make = Effect.gen(function* () { if (Option.isNone(found) || found.value.cleanup === null) return; const row = found.value; const cleanup = found.value.cleanup; - // Not the link's any more: nothing is done to it, and the clean-up ends. - const thread = row.threadId === null ? undefined : yield* ownedThread(deviceId, row.threadId); + // The link's own message is taken back wherever it waits; a thread no + // longer the link's is never stopped for it, and the clean-up ends. + const thread = row.threadId === null ? undefined : yield* readThreadOrFail(row.threadId); const messageId = row.messageId; if ( thread !== undefined && @@ -1357,7 +1374,7 @@ const make = Effect.gen(function* () { now: yield* nowIso, }) .pipe(Effect.mapError(() => peerError(`${ownLabel()} couldn't record the cancel.`))); - const thread = yield* ownedThread(deviceId, threadId); + const thread = yield* readThreadOrFail(threadId); if (thread === undefined) return; const messageId = row.messageId; if ( @@ -1375,23 +1392,26 @@ const make = Effect.gen(function* () { "take back the message of the thread that moved here", ); } - // Only the turn this request asked for: any other is this computer's user's. - const current = yield* ownedThread(deviceId, threadId); - if ( - current !== undefined && - row.turnId !== null && - current.latestTurn?.turnId === row.turnId && - isRunning(current) - ) { - yield* stopIfWorking(deviceId, current); - } + // Only the turn this request's own message started, still the + // newest started here: any later one is this computer's user's. + const current = yield* readThreadOrFail(threadId); + if (current === undefined || !isRunning(current)) return; + const starts = yield* readTurnStarts(threadId); + const newest = [...starts].reduce( + (last, entry) => (last === null || entry[1] > last[1] ? entry : last), + null, + ); + const ownTurn = + (row.turnId !== null && current.latestTurn?.turnId === row.turnId) || + (row.messageId !== null && newest?.[0] === row.messageId); + if (ownTurn) yield* stopIfWorking(deviceId, current, undefined, { asLink: false }); }), ); } yield* closeThread(deviceId, threadId); }); - const closeThread: LinkRequestsShape["closeThread"] = (deviceId, threadId) => + const closeThread = (deviceId: string, threadId: ThreadId) => Effect.gen(function* () { yield* ledger .closeForThread({ linkDeviceId: deviceId, threadId, now: yield* nowIso }) @@ -1531,6 +1551,7 @@ const make = Effect.gen(function* () { ), threadId: row.value.threadId, turnId: TurnId.make(row.value.reportTurnId), + byLink: link.deviceId, createdAt: yield* nowIso, }, "record that its answer reached the thread that asked", @@ -1567,6 +1588,7 @@ const make = Effect.gen(function* () { state: input.override.state, at: input.override.at, fromLinkedComputer: true, + byLink: link.deviceId, }, input.override.state === "done" ? "wrap up that thread" : "reopen that thread", ); @@ -2444,7 +2466,6 @@ const make = Effect.gen(function* () { drainDone, drainsOwed, releaseThread, - closeThread, onTurnEnd, messageVerdict, startReactor, diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 07a1456e5..c60bb7e66 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -57,6 +57,7 @@ import { activeParticipants } from "@threadlines/shared/threadParticipants"; import { handOffReplyText } from "./agentRequestDecisions.ts"; import { isProjectLeadThread } from "./commandInvariants.ts"; +import { NOT_THE_LINKS_THREAD, stillLinksThread } from "./linkFence.ts"; import { checkoutSelectedEvents } from "./threadCheckout.ts"; import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts"; @@ -1225,6 +1226,10 @@ export function decideRemoteHandedBackRecord( command: CommandOf<"thread.remote-handed-back.record">, baseFor: ChildEventBase, ): ChildThreadDecision { + // Only on a thread still that link's (Part 3f, (g)). + if (!stillLinksThread(thread, command.byLink)) { + return refuse(NOT_THE_LINKS_THREAD); + } const latest = thread.latestTurn; if ( latest === null || diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 86e587f22..382bc8dc2 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -1603,3 +1603,118 @@ describe("decider on a child's computer", () => { expect((await run(reopened.model, wrap("done", 25, "late-linked-wrap"))).events).toEqual([]); }); }); + +describe("decider for a link's thread its asker took back (Part 3f, (g))", () => { + const origin = { + linkDeviceId: "device-windows", + environmentId: EnvironmentId.make("env-windows"), + environmentPinned: true, + environmentLabel: "Windows PC", + threadId: ThreadId.make("windows-parent"), + threadTitle: "Ship the 0.6 release", + }; + const running = { + turnId: TurnId.make("user-turn"), + state: "running" as const, + requestedAt: at(1), + startedAt: at(1), + completedAt: null, + assistantMessageId: null, + }; + const session = { + threadId: CHILD, + status: "running" as const, + providerName: "codex", + runtimeMode: "auto" as const, + activeTurnId: TurnId.make("user-turn"), + lastError: null, + updatedAt: at(1), + }; + /** The same thread, still the link's, and taken back as a child here. */ + const stillTheLinks = readModel([ + thread(CHILD, { remoteOrigin: origin, latestTurn: running, session }), + ]); + const takenBack = readModel([ + thread(CHILD, { + remoteOrigin: null, + adoptedFromLink: { environmentId: origin.environmentId, label: "Windows PC", fenced: true }, + latestTurn: running, + session, + }), + ]); + const byLink = { byLink: "device-windows" }; + + it("a stop, a Wrap up or an answer's record the link asked for is refused once it isn't the link's", async () => { + const stop = { + type: "thread.session.stop" as const, + commandId: CommandId.make("link-stop"), + threadId: CHILD, + createdAt: at(10), + ...byLink, + }; + const wrap = { + type: "thread.done-override.set" as const, + commandId: CommandId.make("link-wrap"), + threadId: CHILD, + state: "done" as const, + at: at(10), + fromLinkedComputer: true, + ...byLink, + }; + const record = { + type: "thread.remote-handed-back.record" as const, + commandId: CommandId.make("link-record"), + threadId: CHILD, + turnId: TurnId.make("user-turn"), + createdAt: at(10), + ...byLink, + }; + expect((await run(stillTheLinks, stop)).events.length).toBeGreaterThan(0); + expect((await run(stillTheLinks, wrap)).events.length).toBeGreaterThan(0); + expect(await refused(stillTheLinks, record)).toBe(false); + + expect(await refused(takenBack, stop)).toBe(true); + expect(await refused(takenBack, wrap)).toBe(true); + expect(await refused(takenBack, record)).toBe(true); + // This computer's own stop still stops it. + const { byLink: _, ...own } = stop; + expect((await run(takenBack, own)).events.length).toBeGreaterThan(0); + }); + + it("a link's queued request is taken back, not run, once the thread isn't the link's", async () => { + const messageId = MessageId.make("link-message"); + const queued = { + messageId, + text: "Add the security fixes too.", + attachments: [], + fromThread: { + threadId: origin.threadId, + requestId: ChildRequestId.make("send-1"), + kind: "request" as const, + environmentId: origin.environmentId, + }, + runtimeMode: "auto" as const, + interactionMode: "default" as const, + createdAt: at(2), + }; + const idle = { latestTurn: null, session: null, queuedFollowUps: [queued] }; + const sendQueued = { + type: "thread.follow-up.send-queued" as const, + commandId: CommandId.make("send-queued"), + threadId: CHILD, + messageId, + createdAt: at(10), + }; + const sent = await run( + readModel([thread(CHILD, { remoteOrigin: origin, ...idle })]), + sendQueued, + ); + expect(sent.events.map((event) => event.type)).toContain("thread.turn-start-requested"); + const taken = await run( + readModel([thread(CHILD, { remoteOrigin: null, ...idle })]), + sendQueued, + ); + expect(taken.events.map((event) => event.type)).toEqual(["thread.follow-up-unqueued"]); + expect(taken.events[0]?.payload).toMatchObject({ reason: "cancelled" }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index ebe941540..1d0a81196 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -120,7 +120,7 @@ import { heldRequestEnded, isHeldByContinueAtReset, } from "./childThreadDelivery.ts"; -import { turnLiftsMoveFence } from "./linkFence.ts"; +import { NOT_THE_LINKS_THREAD, stillLinksThread, turnLiftsMoveFence } from "./linkFence.ts"; import { projectEvent } from "./projector.ts"; import { checkoutSelectedEvents, leavesLentWorktree, movesCheckout } from "./threadCheckout.ts"; import { canReplaceThreadTitle } from "./threadTitle.ts"; @@ -2155,7 +2155,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ) { return []; } - // A word from the parent's computer never takes back a newer one given here. + // A word from the parent's computer counts only while the thread is + // still that link's (Part 3f, (g)), and never takes back a newer one + // given here. + if (!stillLinksThread(thread, command.byLink)) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: NOT_THE_LINKS_THREAD, + }); + } const fromLinkedComputer = command.fromLinkedComputer === true; if ( fromLinkedComputer && @@ -4168,6 +4176,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); return [unqueuedEvent, ...outsideTurn]; } + // A linked computer's request runs only while the thread is still that + // computer's (Part 3f, (g)): once the thread that asked took it back + // as a child here, it is taken back, so the queue moves on. + if ( + queued.fromThread?.kind === "request" && + queued.fromThread.environmentId !== undefined && + (targetThread.remoteOrigin?.environmentId !== queued.fromThread.environmentId || + targetThread.remoteOrigin.threadId !== queued.fromThread.threadId) + ) { + return [{ ...unqueuedEvent, payload: { ...unqueuedEvent.payload, reason: "cancelled" } }]; + } // A message an agent queued (a hand-off, a routed reply, or a child // thread's report or request) goes only to the agent it was for. If that // agent left, it is taken back and its request cancelled, never handed @@ -4871,6 +4890,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); + // A linked computer's stop stops only a thread still its own (Part 3f, (g)). + if (!stillLinksThread(thread, command.byLink)) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: NOT_THE_LINKS_THREAD, + }); + } const base = () => withEventBase({ aggregateKind: "thread", diff --git a/apps/server/src/orchestration/linkFence.ts b/apps/server/src/orchestration/linkFence.ts index 781a81bdf..a94192b74 100644 --- a/apps/server/src/orchestration/linkFence.ts +++ b/apps/server/src/orchestration/linkFence.ts @@ -81,3 +81,18 @@ export function linkFenceRefusal(thread: LinkFencedThread, tools: string): strin } return `This thread moved here from ${thread.movedFrom?.label ?? "another computer"}, so it has no ${tools} until the user here sends it a message.`; } + +/** + * Whether what a linked computer asked for over its link (`byLink`, its + * device id) may still act on the thread: nothing names a link, or the + * thread is still that link's (`remoteOrigin`). Asked in the decision + * itself, so a thread its asker took back as a child here (Part 3f, (g)) + * is never stopped, wrapped or marked by a request read before that. + */ +export const stillLinksThread = ( + thread: Pick, + byLink: string | undefined, +): boolean => byLink === undefined || thread.remoteOrigin?.linkDeviceId === byLink; + +/** Why a linked computer's stop, Wrap up or ack is refused on a thread no longer its own. */ +export const NOT_THE_LINKS_THREAD = "This thread isn't one that computer's link started anymore."; diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 1e5e19197..b167a9bfb 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -22,6 +22,9 @@ import { type OrchestrationQueuedFollowUp, type OrchestrationThread, type OrchestrationThreadDoneOverride, + type ProviderInteractionMode, + type RuntimeMode, + type ThreadRemoteOrigin, type OrchestrationThreadMove, type ThreadId, type ThreadMoveFamily, @@ -1954,7 +1957,28 @@ function importedAdoption( seen.add(entry.threadId); const child = readModel.threads.find((thread) => thread.id === entry.threadId); if (child === undefined || child.deletedAt !== null) continue; - const why = adoptionRefusal(readModel, command, asked.linkDeviceId, child); + const why = adoptionRefusal( + { + remoteOrigin: child.remoteOrigin ?? null, + projectId: child.projectId, + archivedAt: child.archivedAt, + moving: (child.move ?? null) !== null || (child.pendingMove ?? null) !== null, + inFamily: + (child.parentThreadId !== null && child.attachedToParent) || + attachedChildrenOf(readModel, child.id).length > 0, + runtimeMode: child.runtimeMode, + interactionMode: child.interactionMode, + }, + { + linkDeviceId: asked.linkDeviceId, + sourceThreadId: command.movedFrom.threadId, + fromEnvironmentId: command.movedFrom.environmentId, + fromPinned: command.movedFrom.environmentPinned === true, + projectId: command.projectId, + runtimeMode: command.runtimeMode, + interactionMode: command.interactionMode, + }, + ); if (why === null) adopted.push({ thread: child, override: entry.override }); else apart.push({ title: child.title, why }); } @@ -1967,62 +1991,74 @@ function importedAdoption( ? `Its thread '${only.thread.title}' was already on this computer. It's this thread's again.` : `Its ${adopted.length} threads already on this computer are this thread's again: ${titlesOf(adopted.map((entry) => entry.thread))}.`, ]; - const left = apart.map( - (entry) => - `Its thread '${entry.title}' is already on this computer. It stays separate because ${entry.why}, so this thread can't reach it.`, - ); + const left = apart.map((entry) => adoptionApartWords(entry.title, entry.why)); return { adopted, brought, left }; } +/** A thread here that the arriving thread's agent may have started over its link, as adoptionRefusal reads it. */ +export interface AdoptionCandidate { + readonly remoteOrigin: ThreadRemoteOrigin | null; + readonly projectId: string; + readonly archivedAt: string | null; + /** Queued to move, or moving. */ + readonly moving: boolean; + /** Attached to a parent here, or a parent of attached threads itself. */ + readonly inFamily: boolean; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; +} + +/** The thread arriving, as its import will write it (its modes after the link's cap). */ +export interface AdoptionArrival { + /** The link the move came over, from the transfer's own record. */ + readonly linkDeviceId: string; + /** The thread it was on the computer it came from. */ + readonly sourceThreadId: string; + readonly fromEnvironmentId: string; + /** The link proved which computer that is. */ + readonly fromPinned: boolean; + readonly projectId: string; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; +} + /** - * Why `child`, a thread here, can't become the arriving thread's child, in - * words that finish "It stays separate because ...", or null. It must be - * one this very link started for the very thread that arrives, from the - * computer that link proved it is; in the arriving thread's project; not - * archived, moving or a parent itself; and asking no more access than the - * arriving thread has here (its modes as this import writes them): a child - * never has more access than its parent, and its access is never lowered - * for it. + * Why `child`, a thread here, can't become the arriving thread's child + * (docs/design/fleet.md, Part 3f, (g)), in words that finish "It stays + * separate because ...", or null. It must be one this very link started for + * the very thread that arrives, from the computer that link proved it is; in + * the arriving thread's project; not archived, moving or in a family here; + * and asking no more access than the arriving thread has here: a child never + * has more access than its parent, and its access is never lowered for it. + * LinkMoves asks it before the link lets go of a thread, and the decider + * again in the import's decision, so one that fails is never released. */ -function adoptionRefusal( - readModel: OrchestrationReadModel, - command: CommandOf<"thread.import">, - linkDeviceId: string, - child: OrchestrationThread, -): string | null { - const origin = child.remoteOrigin ?? null; +export function adoptionRefusal(child: AdoptionCandidate, arrival: AdoptionArrival): string | null { + const origin = child.remoteOrigin; if ( origin === null || - origin.linkDeviceId !== linkDeviceId || - origin.threadId !== command.movedFrom.threadId || + origin.linkDeviceId !== arrival.linkDeviceId || + origin.threadId !== arrival.sourceThreadId || origin.environmentPinned !== true || - command.movedFrom.environmentPinned !== true || - origin.environmentId !== command.movedFrom.environmentId + !arrival.fromPinned || + origin.environmentId !== arrival.fromEnvironmentId ) { return "this computer can't confirm this thread started it"; } - if (child.projectId !== command.projectId) return "it's in another project here"; + if (child.projectId !== arrival.projectId) return "it's in another project here"; if (child.archivedAt !== null) return "it's archived"; - if ((child.move ?? null) !== null || (child.pendingMove ?? null) !== null) { - return "it's moving"; - } - if ( - (child.parentThreadId !== null && child.attachedToParent) || - attachedChildrenOf(readModel, child.id).length > 0 - ) { - return "it's in another family here"; - } - if ( - !withinModeCeiling(child, { - runtimeMode: command.runtimeMode, - interactionMode: command.interactionMode, - }) - ) { + if (child.moving) return "it's moving"; + if (child.inFamily) return "it's in another family here"; + if (!withinModeCeiling(child, arrival)) { return "it has more access than this thread has here"; } return null; } +/** The "Moved here" words for a thread it started here that stays apart, and why. */ +export const adoptionApartWords = (title: string, why: string) => + `Its thread '${title}' is already on this computer. It stays separate because ${why}, so this thread can't reach it.`; + /** * Each adopted thread becomes the arriving thread's child (no parent turn, a * fresh attachment epoch, so nothing owed under its old one comes back), diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 4a41ce727..e9d0096ac 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -465,6 +465,20 @@ const makeProjectionThreadRepository = Effect.gen(function* () { `, }); + const listAttachedChildIdsRows = SqlSchema.findAll({ + Request: ListProjectionAdoptedChildrenInput, + Result: Schema.Struct({ threadId: ThreadId }), + execute: ({ parentThreadId }) => + sql` + SELECT thread_id AS "threadId" + FROM projection_threads + WHERE parent_thread_id = ${parentThreadId} + AND attached_to_parent > 0 + AND deleted_at IS NULL + ORDER BY created_at ASC, thread_id ASC + `, + }); + const deleteProjectionThreadRow = SqlSchema.void({ Request: DeleteProjectionThreadInput, execute: ({ threadId }) => @@ -505,6 +519,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ), ); + const listAttachedChildIds: ProjectionThreadRepositoryShape["listAttachedChildIds"] = (input) => + listAttachedChildIdsRows(input).pipe( + Effect.map((rows) => rows.map((row) => row.threadId)), + Effect.mapError( + toPersistenceSqlError("ProjectionThreadRepository.listAttachedChildIds:query"), + ), + ); + const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) => deleteProjectionThreadRow(input).pipe( Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.deleteById:query")), @@ -516,6 +538,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { listByProjectId, listIdsByRemoteLink, listAdoptedChildIds, + listAttachedChildIds, deleteById, } satisfies ProjectionThreadRepositoryShape; }); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 6a34a0ce6..2d518bfd4 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -314,6 +314,11 @@ export interface ProjectionThreadRepositoryShape { input: ListProjectionAdoptedChildrenInput, ) => Effect.Effect, ProjectionRepositoryError>; + /** Ids of `parentThreadId`'s attached children that aren't deleted. */ + readonly listAttachedChildIds: ( + input: ListProjectionAdoptedChildrenInput, + ) => Effect.Effect, ProjectionRepositoryError>; + /** * Soft-delete a projected thread row by id. */ diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 74973735e..8fcf1c47f 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1385,12 +1385,12 @@ A child that isn't in the set, or whose own move failed after the parent's commi - **`RemoteChildReactor` learns about moves.** It reads only `id`, `title`, `participants`, `childRequests`, `archivedAt` and `deletedAt` today. It now skips a parent with `move` set for watches and for anything that writes to the parent. One exception: `thread.remote-cancels.delivered` joins `FROZEN_THREAD_COMMANDS`, so cancels owed at the freeze still drain. - **A hole this closes.** On a frozen parent the reactor's four commands are refused. It reads a refused settle as "settled meanwhile" and acks the report as not delivered (RemoteChildReactor.ts ~609-619), so the answer is lost. No frozen parent can have remote children today, so it can't happen yet. Skipping frozen parents makes sure it never does. - **Also when the child's computer is the target (Nov 18: taken back on arrival).** Kept apart, such a thread was stranded: fenced for good, pointing at a read-only copy, its reports retried forever, and nobody could direct it. So the parent takes it back as its child there. - - **Who.** A thread both lists name: the sender's `remoteChildren` on the target (`PeerMoveManifest.startedThere`, at most 50, each with the user's pending Wrap up or Reopen), and the target's own records (threads started over this very link by the thread the move came from, not archived, deleted or moved away). The sender sends the list only to a computer that says `PeerDescriptor.moveAdoptsChildren`; an older one keeps them apart, with the line below. Only a thread that lands on its own (no `lineage`, `remoteOrigin` or `adopt`) takes any back; a family's parent does. + - **Who.** A thread both lists name: the sender's `remoteChildren` on the target (`PeerMoveManifest.startedThere`, at most 50, each with the user's pending Wrap up or Reopen), and the target's own records (threads started over this very link by the thread the move came from, not deleted or moved away). Of those, only threads that pass the decider's checks below (`adoptionRefusal`, asked once before the release with the modes the import will write, and again in the decision) are released and taken back; one that fails, archived ones included, keeps what its link asked of it, and the "Moved here" line says why. The sender sends the list only to a computer that says `PeerDescriptor.moveAdoptsChildren`; an older one keeps them apart, with the line below. Only a thread that lands on its own (no `lineage`, `remoteOrigin` or `adopt`) takes any back; a family's parent does. - **Checks, per thread, in the decider** (`thread.import`'s `adoptsChildren`, with the link from the transfer's row, never the manifest). Its `remoteOrigin` is this link, names the thread the move came from, and is pinned to the computer the move came from; it is in the same project; it isn't archived, moving or queued to move; it has no attached children; and it asks no more access than the arriving thread has there (its modes as the import writes them, after the link's cap). One that fails stays as it is, never with its access lowered, and the "Moved here" line says why. The import never fails for it. - **What it becomes.** In the same decision: `remoteOrigin` is cleared, it is the arriving thread's attached child (no parent turn, a fresh attachment epoch), and it carries `adoptedFromLink { environmentId, label, fenced: true }` (`thread.parent-attachment-set` with `adoptedBy`). A newer Wrap up or Reopen from the list stands, as `fromLinkedComputer` decides. Its timeline says what happened. - **The fence.** It works behind the link fence until a message the user sends in it there lifts it (the moved-thread rule, `turnLiftsMoveFence`). That is Will's call (Nov 18): the user there taking it over is the same proof a moved thread needs. A message in the parent, a `fromThread` send, or a scheduled run doesn't lift it. While fenced it moves only back to `adoptedFromLink.environmentId`. - - **The link lets go first.** Under the transfer lock, before the import, each thread is released (`LinkRequests.releaseThread`): every open request of the link's for it ends cancelled ("The thread that asked moved here."), its queued message is taken back, it is stopped only while the running turn is that request's, and the ledger owes the link nothing more for it (`closeForThread`: reports marked delivered, clean-up and owed stops cleared). After the import lands this runs again for the threads the parent holds. If the import fails, they stay the link's, with those requests ended. - - **Ownership.** Everything the link does to a thread asks first that the thread is still the link's (`ownedThread`): a cancel's clean-up (live and at startup), an ack, send, read, stop and wrap. So the sender's late `peer.request.cancel { stopThread }` stops nothing the user started there since. + - **The link lets go first.** Under the transfer lock, before the import, each thread is released (`LinkRequests.releaseThread`): every open request of the link's for it ends cancelled ("The thread that asked moved here."), its queued message is taken back, it is stopped only while the turn running was started by that request's own message and is still the newest started there (read from the thread's turn starts, so a turn the user started since is never stopped), and the ledger owes the link nothing more for it (`closeForThread`: reports marked delivered, clean-up and owed stops cleared). After the import lands this runs again for the threads the parent holds, so a request that arrived between the release and the import ends too and its message is taken back. If the import fails, they stay the link's, with those requests ended. + - **Ownership.** Everything the link does to a thread asks first that the thread is still the link's (`ownedThread`): a cancel's clean-up (live and at startup), an ack, send, read, stop and wrap. That read can be stale by the time its command lands, so the decider is the guard: a stop, Wrap up or answer's record the link asks for names it (`byLink`) and is refused unless the thread is still that link's, and a link's queued request (`fromThread` naming that computer) is taken back instead of run once the thread isn't. So the sender's late `peer.request.cancel { stopThread }` stops nothing the user started there since. - **The answer.** The committed `PeerMoveState.adopted` names them, read from the threads (so a restart between import and answer still says it). `thread.move.complete { adopted }` removes their `remoteChildren` entries from the read-only copy and settles any request still open for them. `RemoteChildReactor` acks a report for a parent that moved away as not delivered, so the target stops offering it. - **Words.** On the parent: "Its thread 'Fix tests' was already on this computer. It's this thread's again." One kept apart: "Its thread 'Fix tests' is already on this computer. It stays separate because it has more access than this thread has here, so this thread can't reach it." A thread in the target's records but not on the list (an older sender) gets today's line: "Its thread 'Fix tests' is already on this computer. It stays separate, so this thread can't reach it." The sender leaves them out of `remoteStayed`, which would otherwise say they "stayed there". The move dialog says "'Fix tests' on Mac mini becomes its thread there again." to a target that takes them. diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index b011b138b..4822e32de 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3764,6 +3764,8 @@ const ThreadDoneOverrideSetCommand = Schema.Struct({ * `at` unless it was seen later, in the same step. */ fromLinkedComputer: Schema.optional(Schema.Boolean), + /** See ThreadSessionStopCommand.byLink. */ + byLink: Schema.optional(TrimmedNonEmptyString), }); /** @@ -4322,6 +4324,14 @@ const ThreadSessionStopCommand = Schema.Struct({ type: Schema.Literal("thread.session.stop"), commandId: CommandId, threadId: ThreadId, + /** + * Server only: a linked computer asked for it over its link (this device + * id). It does nothing unless the thread is still that link's + * (`remoteOrigin`), decided atomically with the stop, so a thread its + * asker took back as a child here (ThreadAdoptedFromLink) is never stopped + * by a request that was read before that. + */ + byLink: Schema.optional(TrimmedNonEmptyString), createdAt: IsoDateTime, }); @@ -5273,6 +5283,8 @@ const ThreadRemoteHandedBackRecordCommand = Schema.Struct({ commandId: CommandId, threadId: ThreadId, turnId: TurnId, + /** See ThreadSessionStopCommand.byLink. */ + byLink: Schema.optional(TrimmedNonEmptyString), createdAt: IsoDateTime, }); From d66cfc29bf6de92d5c1f0bae4f3991fe61e6123c Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:54:34 -0500 Subject: [PATCH 3/3] fix(server): release stops only the link's own turn, and a refused link stop is kept - A stop can name the turn it means (`thread.session.stop.expectedTurnId`); the decider refuses it when another turn began before it landed. Release uses it, so it never ends the user's next turn. - Release decides and dispatches its stop before it marks the request ended, so a retry after a failed read decides it again. A failed release after the import leaves the move unsettled for the sweep to redo. - A link's stop answers "not yours" only for the ownership refusal; any other refusal fails as before, so the asking computer keeps the stop. - fleet.md names the window where a thread queues its own move between the check and the import. --- apps/server/src/links/LinkMoves.ts | 5 +- apps/server/src/links/LinkRequests.test.ts | 76 ++++++++++- apps/server/src/links/LinkRequests.ts | 128 ++++++++++++------ .../decider.childThreads.test.ts | 37 +++++ apps/server/src/orchestration/decider.ts | 15 +- docs/design/fleet.md | 2 +- packages/contracts/src/orchestration.ts | 6 + 7 files changed, 220 insertions(+), 49 deletions(-) diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 1dececacc..25a19ba9f 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -2516,14 +2516,15 @@ const make = Effect.gen(function* () { * are let go by the link again (LinkRequests.releaseThread), so a request * that arrived between their release and the import ends too, and its * message is taken back. Read from the projection, so a restart in between - * finishes it. + * finishes it. One that fails leaves the move unsettled (`importing`), so + * the sweep tries the whole of it again before it settles. */ const releaseAdopted = (row: LinkMoveRow) => Effect.gen(function* () { const adopted = yield* threadRows.listAdoptedChildIds({ parentThreadId: row.threadId }); for (const threadId of adopted) yield* requests.releaseThread(row.linkDeviceId, threadId); }).pipe( - Effect.catch((error) => + Effect.tapError((error) => Effect.logWarning("a moved thread's adopted threads couldn't be released by their link", { threadId: row.threadId, detail: String(error), diff --git a/apps/server/src/links/LinkRequests.test.ts b/apps/server/src/links/LinkRequests.test.ts index c2fb9fae2..37dc8ef1e 100644 --- a/apps/server/src/links/LinkRequests.test.ts +++ b/apps/server/src/links/LinkRequests.test.ts @@ -49,6 +49,7 @@ import { type ProjectionSnapshotQueryShape, } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { PersistenceSqlError } from "../persistence/Errors.ts"; +import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts"; import { ThreadBootstrap, type ThreadBootstrapShape, @@ -1650,7 +1651,7 @@ it.layer(NodeServices.layer)("LinkRequests", (it) => { const before = stopsFor(yield* computer.events, threadId); const late = yield* bootReadingStale(computer, threadId, stale); - yield* late.stopThread(link(), threadId); + assert.equal((yield* late.stopThread(link(), threadId)).status, "not_yours"); yield* late.wrapThread(link(), { threadId, override: { state: "done", at: AT } }); yield* late.ack(link(), { reportId: "send-1:report", delivered: true }); assert.equal(stopsFor(yield* computer.events, threadId), before); @@ -1671,8 +1672,19 @@ it.layer(NodeServices.layer)("LinkRequests", (it) => { yield* userTurnRunning(asked, first.threadId, "turn-asked"); assert.isNull((yield* asked.request("request-1")).turnId); const before = stopsFor(yield* asked.events, first.threadId); - yield* first.service.releaseThread(DEVICE, first.threadId); + // The stop names the turn it means, so it can never end the next one. + const stops: Array = []; + const recording = yield* asked.boot({ + engine: { + dispatch: (command) => { + if (command.type === "thread.session.stop") stops.push(command.expectedTurnId); + return asked.engine.dispatch(command); + }, + }, + }); + yield* recording.releaseThread(DEVICE, first.threadId); assert.equal(stopsFor(yield* asked.events, first.threadId), before + 1); + assert.deepEqual(stops, ["turn-asked"]); // The user started a turn here since: that one runs on. const mine = yield* makeComputer(); @@ -1700,6 +1712,66 @@ it.layer(NodeServices.layer)("LinkRequests", (it) => { }), ); + it.effect( + "release decides its stop before it ends the request, so a retry decides it again", + () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { threadId } = yield* startedChild(computer, "request-1"); + yield* userTurnRunning(computer, threadId, "turn-asked"); + let unreadable = true; + const service = yield* computer.boot({ + snapshots: { + getThreadDetailById: (id: ThreadId) => + unreadable + ? Effect.fail( + new PersistenceSqlError({ operation: "getThreadDetailById", detail: "busy" }), + ) + : computer.snapshots.getThreadDetailById(id), + }, + }); + const before = stopsFor(yield* computer.events, threadId); + yield* Effect.flip(service.releaseThread(DEVICE, threadId)); + // Still open: nothing was decided. + assert.notEqual((yield* computer.request("request-1")).status, "cancelled"); + unreadable = false; + yield* service.releaseThread(DEVICE, threadId); + assert.equal(stopsFor(yield* computer.events, threadId), before + 1); + assert.equal((yield* computer.request("request-1")).status, "cancelled"); + }), + ); + + it.effect( + "a link's stop refused for any reason but ownership fails, so the asker keeps it and tries again", + () => + Effect.gen(function* () { + const computer = yield* makeComputer(); + yield* computer.addLink(DEVICE, "allowed", "active", WINDOWS); + const { threadId } = yield* startedChild(computer, "request-1"); + yield* userTurnRunning(computer, threadId, "turn-asked"); + // Frozen for a move, say: the stop is refused, and the thread is still the link's. + const frozen = yield* computer.boot({ + engine: { + dispatch: (command) => + command.type === "thread.session.stop" + ? Effect.fail( + new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "This thread is moving to Linux box.", + }), + ) + : computer.engine.dispatch(command), + }, + }); + yield* Effect.flip(frozen.stopThread(link(), threadId)); + yield* Effect.flip( + frozen.cancel(link(), ChildRequestId.make("request-1"), { stopThread: true }), + ); + assert.equal((yield* computer.request("request-1")).cleanup, "stop"); + }), + ); + it.effect( "a send that landed between the release and the take-back ends, and its message is taken back", () => diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 2fba97480..603c25a1c 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -82,6 +82,8 @@ import { childReasoningRefusal, } from "../orchestration/childThreadAgents.ts"; import { clampLaunchToCeiling, movingChildRefusal } from "../orchestration/childThreadDecisions.ts"; +import { turnBeingStopped } from "../orchestration/decider.ts"; +import { NOT_THE_LINKS_THREAD } from "../orchestration/linkFence.ts"; import { type ChildDelivery, type ChildDeliveryRequest, @@ -579,6 +581,16 @@ const make = Effect.gen(function* () { }), ); + /** Whether `error` is the engine refusing a command for `detail` (now, or this command id before). */ + const refusedFor = (error: unknown, detail: string) => { + const tagged = error as { readonly _tag?: string; readonly detail?: string }; + return ( + (tagged._tag === "OrchestrationCommandInvariantError" || + tagged._tag === "OrchestrationCommandPreviouslyRejectedError") && + (tagged.detail ?? "").includes(detail) + ); + }; + /** A dispatch the asking computer must hear failed, so it tries again. */ const mustDispatch = (command: OrchestrationCommand, what: string) => dispatch(command, what).pipe( @@ -1245,40 +1257,80 @@ const make = Effect.gen(function* () { * didn't take), not a replay of the first. The stop names the link * (`byLink`), so the decider refuses it when the thread stopped being the * link's after it was read here (its asker took it back, Part 3f, (g)): - * that refusal is an answer (`not_yours`), not a failure. `asLink: false` - * is this computer's own stop, of a turn it found the link's request - * started. + * that refusal is an answer (`not_yours`). Any other refusal fails, as any + * failed stop does, so the asker keeps the stop and tries again. */ - const stopIfWorking = ( - deviceId: string, - thread: OrchestrationThread, - retry?: string, - options: { readonly asLink?: boolean } = {}, - ) => + const stopIfWorking = (deviceId: string, thread: OrchestrationThread, retry?: string) => Effect.gen(function* () { if (!isWorking(thread)) return "not_running" as const; - const command: OrchestrationCommand = { - type: "thread.session.stop", - commandId: CommandId.make( - `server:link-stop:${deviceId}:${thread.id}:${turnKeyOf(thread)}${ - retry === undefined ? "" : `:retry:${retry}` - }`, - ), - threadId: thread.id, - ...(options.asLink === false ? {} : { byLink: deviceId }), - createdAt: yield* nowIso, - }; - if (options.asLink === false) { - yield* mustDispatch(command, "stop that thread"); - return "stopped" as const; + return yield* engine + .dispatch({ + type: "thread.session.stop", + commandId: CommandId.make( + `server:link-stop:${deviceId}:${thread.id}:${turnKeyOf(thread)}${ + retry === undefined ? "" : `:retry:${retry}` + }`, + ), + threadId: thread.id, + byLink: deviceId, + createdAt: yield* nowIso, + }) + .pipe( + Effect.as("stopped" as const), + Effect.catch((error) => + refusedFor(error, NOT_THE_LINKS_THREAD) + ? Effect.succeed("not_yours" as const) + : Effect.logInfo("link requests could not stop that thread", { + detail: String(error), + }).pipe( + Effect.andThen( + Effect.fail(peerError(`${ownLabel()} couldn't stop that thread.`)), + ), + ), + ), + ); + }); + + /** + * Stops the turn `row`'s own message started in `threadId`, if that turn + * is still running and still the newest started there (read from the + * thread's turn starts: the ledger has no turn id while it runs). The stop + * names that turn (`expectedTurnId`), so should the turn end and another + * (the user's) begin before it lands, the decider refuses it, and this + * looks again. Fails when it can't tell or the stop isn't recorded. + */ + const stopRequestTurn = (deviceId: string, threadId: ThreadId, row: LinkRequestRow) => + Effect.gen(function* () { + for (let attempt = 0; attempt < 3; attempt += 1) { + const current = yield* readThreadOrFail(threadId); + if (current === undefined || !isRunning(current)) return; + const starts = yield* readTurnStarts(threadId); + const newest = [...starts].reduce( + (last, entry) => (last === null || entry[1] > last[1] ? entry : last), + null, + ); + const ownTurn = + (row.turnId !== null && current.latestTurn?.turnId === row.turnId) || + (row.messageId !== null && newest?.[0] === row.messageId); + if (!ownTurn) return; + const expectedTurnId = turnBeingStopped(current) ?? null; + const stopped = yield* dispatchUnlessRefused( + { + type: "thread.session.stop", + commandId: linkCommandId( + deviceId, + row.requestId, + `release-stop:${expectedTurnId ?? "none"}:${attempt}`, + ), + threadId, + expectedTurnId, + createdAt: yield* nowIso, + }, + "stop the turn the request started", + ); + if (stopped === "ok") return; } - const stopped = yield* dispatchUnlessRefused(command, "stop that thread"); - if (stopped === "ok") return "stopped" as const; - // Refused: either no longer the link's, or for a reason a retry won't change. - const now = yield* readThreadOrFail(thread.id); - return now !== undefined && now.remoteOrigin?.linkDeviceId === deviceId - ? ("not_running" as const) - : ("not_yours" as const); + return yield* peerError(`${ownLabel()} couldn't stop the turn the request started.`); }); /** @@ -1363,6 +1415,9 @@ const make = Effect.gen(function* () { const found = yield* readRequest(deviceId, listed.requestId); if (Option.isNone(found) || isTerminalLinkRequest(found.value)) return; const row = found.value; + // Its own turn is stopped while the request is still open, so a + // retry after anything that fails here decides it again. + yield* stopRequestTurn(deviceId, threadId, row); // Ended, not published: the asker's copy of its thread moved away, // and closeForThread below marks the report delivered. yield* ledger @@ -1392,19 +1447,6 @@ const make = Effect.gen(function* () { "take back the message of the thread that moved here", ); } - // Only the turn this request's own message started, still the - // newest started here: any later one is this computer's user's. - const current = yield* readThreadOrFail(threadId); - if (current === undefined || !isRunning(current)) return; - const starts = yield* readTurnStarts(threadId); - const newest = [...starts].reduce( - (last, entry) => (last === null || entry[1] > last[1] ? entry : last), - null, - ); - const ownTurn = - (row.turnId !== null && current.latestTurn?.turnId === row.turnId) || - (row.messageId !== null && newest?.[0] === row.messageId); - if (ownTurn) yield* stopIfWorking(deviceId, current, undefined, { asLink: false }); }), ); } diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 382bc8dc2..301c0399f 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -1718,3 +1718,40 @@ describe("decider for a link's thread its asker took back (Part 3f, (g))", () => expect(taken.events[0]?.payload).toMatchObject({ reason: "cancelled" }); }); }); + +describe("decider: a stop meant for one turn", () => { + const turn = (turnId: string) => ({ + latestTurn: { + turnId: TurnId.make(turnId), + state: "running" as const, + requestedAt: at(1), + startedAt: at(1), + completedAt: null, + assistantMessageId: null, + }, + session: { + threadId: CHILD, + status: "running" as const, + providerName: "codex", + runtimeMode: "auto" as const, + activeTurnId: TurnId.make(turnId), + lastError: null, + updatedAt: at(1), + }, + }); + const stop = (expectedTurnId: string | null) => ({ + type: "thread.session.stop" as const, + commandId: CommandId.make(`stop-${expectedTurnId}`), + threadId: CHILD, + expectedTurnId: expectedTurnId === null ? null : TurnId.make(expectedTurnId), + createdAt: at(10), + }); + + it("never ends the turn that began after it was decided", async () => { + // The link's turn ended and the user's began before the stop landed. + const usersTurn = readModel([thread(CHILD, turn("user-turn"))]); + expect(await refused(usersTurn, stop("link-turn"))).toBe(true); + expect(await refused(usersTurn, stop(null))).toBe(true); + expect((await run(usersTurn, stop("user-turn"))).events.length).toBeGreaterThan(0); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 1d0a81196..0487e12e1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1228,7 +1228,10 @@ const decideWaitEndOnStop = Effect.fn("decideWaitEndOnStop")(function* ( }); /** The turn a Stop is for: the one running now, if any. */ -function turnBeingStopped(thread: OrchestrationThread): TurnId | undefined { +/** Why a stop meant for one turn is refused: the thread is at another one. */ +export const STOP_TURN_MOVED_ON = "The turn it meant to stop isn't the one running now."; + +export function turnBeingStopped(thread: OrchestrationThread): TurnId | undefined { return ( thread.session?.activeTurnId ?? (thread.latestTurn?.state === "running" ? thread.latestTurn.turnId : undefined) ?? @@ -4897,6 +4900,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: NOT_THE_LINKS_THREAD, }); } + // A stop meant for one turn never ends the next. + if ( + command.expectedTurnId !== undefined && + (turnBeingStopped(thread) ?? null) !== command.expectedTurnId + ) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: STOP_TURN_MOVED_ON, + }); + } const base = () => withEventBase({ aggregateKind: "thread", diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 8fcf1c47f..91d897ad9 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1389,7 +1389,7 @@ A child that isn't in the set, or whose own move failed after the parent's commi - **Checks, per thread, in the decider** (`thread.import`'s `adoptsChildren`, with the link from the transfer's row, never the manifest). Its `remoteOrigin` is this link, names the thread the move came from, and is pinned to the computer the move came from; it is in the same project; it isn't archived, moving or queued to move; it has no attached children; and it asks no more access than the arriving thread has there (its modes as the import writes them, after the link's cap). One that fails stays as it is, never with its access lowered, and the "Moved here" line says why. The import never fails for it. - **What it becomes.** In the same decision: `remoteOrigin` is cleared, it is the arriving thread's attached child (no parent turn, a fresh attachment epoch), and it carries `adoptedFromLink { environmentId, label, fenced: true }` (`thread.parent-attachment-set` with `adoptedBy`). A newer Wrap up or Reopen from the list stands, as `fromLinkedComputer` decides. Its timeline says what happened. - **The fence.** It works behind the link fence until a message the user sends in it there lifts it (the moved-thread rule, `turnLiftsMoveFence`). That is Will's call (Nov 18): the user there taking it over is the same proof a moved thread needs. A message in the parent, a `fromThread` send, or a scheduled run doesn't lift it. While fenced it moves only back to `adoptedFromLink.environmentId`. - - **The link lets go first.** Under the transfer lock, before the import, each thread is released (`LinkRequests.releaseThread`): every open request of the link's for it ends cancelled ("The thread that asked moved here."), its queued message is taken back, it is stopped only while the turn running was started by that request's own message and is still the newest started there (read from the thread's turn starts, so a turn the user started since is never stopped), and the ledger owes the link nothing more for it (`closeForThread`: reports marked delivered, clean-up and owed stops cleared). After the import lands this runs again for the threads the parent holds, so a request that arrived between the release and the import ends too and its message is taken back. If the import fails, they stay the link's, with those requests ended. + - **The link lets go first.** Under the transfer lock, before the import, each thread is released (`LinkRequests.releaseThread`): every open request of the link's for it ends cancelled ("The thread that asked moved here."), its queued message is taken back, it is stopped only while the turn running was started by that request's own message and is still the newest started there (read from the thread's turn starts, so a turn the user started since is never stopped; the stop names that turn, `expectedTurnId`, and the decider refuses it if another began before it lands), all decided before the request is marked ended so a retry decides it again, and the ledger owes the link nothing more for it (`closeForThread`: reports marked delivered, clean-up and owed stops cleared). After the import lands this runs again for the threads the parent holds, so a request that arrived between the release and the import ends too and its message is taken back. If the import fails, they stay the link's, with those requests ended. A known window, left open on purpose: a thread that queues its own move after the check but before the import isn't taken back, and still loses the requests the release ended. - **Ownership.** Everything the link does to a thread asks first that the thread is still the link's (`ownedThread`): a cancel's clean-up (live and at startup), an ack, send, read, stop and wrap. That read can be stale by the time its command lands, so the decider is the guard: a stop, Wrap up or answer's record the link asks for names it (`byLink`) and is refused unless the thread is still that link's, and a link's queued request (`fromThread` naming that computer) is taken back instead of run once the thread isn't. So the sender's late `peer.request.cancel { stopThread }` stops nothing the user started there since. - **The answer.** The committed `PeerMoveState.adopted` names them, read from the threads (so a restart between import and answer still says it). `thread.move.complete { adopted }` removes their `remoteChildren` entries from the read-only copy and settles any request still open for them. `RemoteChildReactor` acks a report for a parent that moved away as not delivered, so the target stops offering it. - **Words.** On the parent: "Its thread 'Fix tests' was already on this computer. It's this thread's again." One kept apart: "Its thread 'Fix tests' is already on this computer. It stays separate because it has more access than this thread has here, so this thread can't reach it." A thread in the target's records but not on the list (an older sender) gets today's line: "Its thread 'Fix tests' is already on this computer. It stays separate, so this thread can't reach it." The sender leaves them out of `remoteStayed`, which would otherwise say they "stayed there". The move dialog says "'Fix tests' on Mac mini becomes its thread there again." to a target that takes them. diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 4822e32de..f753a3832 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -4332,6 +4332,12 @@ const ThreadSessionStopCommand = Schema.Struct({ * by a request that was read before that. */ byLink: Schema.optional(TrimmedNonEmptyString), + /** + * Server only: the turn it means to stop (null: no turn has started yet). + * Refused when the thread is at another turn by then, so a stop decided + * for one turn never ends the next one, which may be the user's. + */ + expectedTurnId: Schema.optional(Schema.NullOr(TurnId)), createdAt: IsoDateTime, });