diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index bd49d2553..08f62c8d1 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -107,6 +107,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function threadMoveQueue: true, threadMoveBatch: true, threadMoveStagedApproval: true, + threadMoveState: true, projectSetup: true, stallReports: true, pullRequestObservations: true, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 7bb9b1e8c..591a89f16 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -140,7 +140,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. A thread in a room, that started other threads, or that has a goal, a check-back, queued messages or pull request auto-fix on can't move yet; the dialog says what to finish first. General Chats don't move.`, +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, pull request auto-fix and auto-merge keep watching from there (switched off, with why, when its branch had to be renamed there), and its plans come along, the waiting one with Implement. 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 thread in a room, that started other threads, or with a message queued by a scheduled task, another thread or an assistant can't move yet; the dialog says what to finish first.`, }, { id: "devices", diff --git a/apps/server/src/links/LinkMoveRepository.ts b/apps/server/src/links/LinkMoveRepository.ts index bb03c8dd5..9420233f5 100644 --- a/apps/server/src/links/LinkMoveRepository.ts +++ b/apps/server/src/links/LinkMoveRepository.ts @@ -38,8 +38,19 @@ export const LinkMoveStatus = Schema.Literals([ ]); export type LinkMoveStatus = typeof LinkMoveStatus.Type; -/** How far an import got; each stage is recorded before the next starts. */ -export const LinkMoveStage = Schema.Literals(["fetched", "worktree", "applied"]); +/** + * How far an import got; each stage is recorded before the next starts. A + * thread with a checkout goes fetched, worktree, applied; a General Chats + * thread goes folder, applied. `arrived`, on a committed move: its arrival + * was sent (the queue's head), so a restart doesn't send it again. + */ +export const LinkMoveStage = Schema.Literals([ + "fetched", + "worktree", + "folder", + "applied", + "arrived", +]); export type LinkMoveStage = typeof LinkMoveStage.Type; export const LinkMoveRow = Schema.Struct({ @@ -136,6 +147,14 @@ export interface LinkMoveRepositoryShape { readonly transferId: string; readonly now: string; }) => Effect.Effect; + /** A committed move's arrival was sent (stage `arrived`). */ + readonly markArrived: (input: { + readonly linkDeviceId: string; + readonly transferId: string; + readonly now: string; + }) => Effect.Effect; + /** Committed moves whose arrival may not have been sent yet, oldest first. */ + readonly listUnarrived: Effect.Effect, LinkMoveRepositoryError>; } export class LinkMoveRepository extends Context.Service< @@ -272,8 +291,23 @@ const make = Effect.gen(function* () { WHERE link_device_id = ${input.linkDeviceId} AND transfer_id = ${input.transferId} `.pipe(Effect.asVoid, wrap("markCleaned")); + const markArrived: LinkMoveRepositoryShape["markArrived"] = (input) => + sql` + UPDATE link_moves SET stage = 'arrived', updated_at = ${input.now} + WHERE link_device_id = ${input.linkDeviceId} AND transfer_id = ${input.transferId} + AND status = 'committed' + `.pipe(Effect.asVoid, wrap("markArrived")); + + const listUnarrived: LinkMoveRepositoryShape["listUnarrived"] = findMany( + `status = 'committed' AND (stage IS NULL OR stage <> 'arrived')`, + [], + ).pipe(wrap("listUnarrived")); + return LinkMoveRepository.of({ + markArrived, + listUnarrived, insert, + get, listOpen, listCleanupOwed, diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index 12f336930..e427f6fdf 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -13,9 +13,13 @@ import { ProviderInstanceId, ThreadId, ThreadMoveId, + TurnId, + GENERAL_CHATS_PROJECT_ID, type OrchestrationCommand, type OrchestrationThread, + type OrchestrationThreadShell, type PeerMoveManifest, + type PeerMoveThreadState, } from "@threadlines/contracts"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -31,6 +35,7 @@ import { inspectMoveCheckout, movePayloadPath, writeMoveExport, + writeScratchExport, } from "../moves/moveExport.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; @@ -42,6 +47,7 @@ import { importClaudeNativeSession, } from "../provider/Drivers/ClaudeNativeSession.ts"; import type { NativeSessionExport } from "../provider/nativeSession.ts"; +import type { ProviderAdapterCapabilities } from "../provider/Services/ProviderAdapter.ts"; import { ProviderService, type ProviderServiceShape, @@ -53,6 +59,7 @@ import { LinkMoveRepositoryLive } from "./LinkMoveRepository.ts"; import { binaryPatchBytes, linkMoveKey, + linkMoveThreadId, LinkMoves, LinkMovesLive, MAX_STAGED_MOVES_PER_LINK, @@ -154,6 +161,12 @@ interface CarryRecord { readonly forgotten?: Array; /** The engine fails to create the moved thread. */ readonly failImport?: boolean; + /** What the agent here keeps of a moved thread (docs/design/fleet.md, Part 3e). */ + readonly capabilities?: Partial; + /** This computer's General Chats folder, for a general chat that moves here. */ + readonly generalChatsRoot?: string; + /** The moved thread as it reads here once it landed (its queue, its session). */ + readonly shell?: () => OrchestrationThreadShell | undefined; } /** The services LinkMoves leans on, with this computer's git real and the rest faked. */ @@ -213,6 +226,22 @@ function testLayer( }), Layer.mock(ProjectionSnapshotQuery)({ getCommandReadModel: () => Effect.succeed({ threads: [], projects: [] } as never), + getProjectCatalog: () => + Effect.succeed({ + projects: + carry.generalChatsRoot === undefined + ? [] + : [ + { + id: GENERAL_CHATS_PROJECT_ID, + kind: "general-chat", + title: "General Chats", + workspaceRoot: carry.generalChatsRoot, + deletedAt: null, + }, + ], + } as never), + getThreadShellById: () => Effect.succeed(Option.fromUndefinedOr(carry.shell?.())), }), Layer.mock(ProjectionThreadRepository)({ getById: () => Effect.succeed(Option.none()) }), Layer.mock(RelayDeviceRepository)({ getDevice: () => Effect.succeed(Option.none()) }), @@ -223,6 +252,12 @@ function testLayer( importNativeSession: ({ instanceId: _instanceId, ...input }) => importClaudeNativeSession({ ...input, configDir: carry.home }), adoptNativeSession: (input) => Effect.sync(() => void carry.adopted.push(input)), + getCapabilities: () => + Effect.succeed({ + sessionModelSwitch: "in-session", + threadGoals: "supported", + ...carry.capabilities, + } as ProviderAdapterCapabilities), forgetNativeSession: (threadId) => Effect.sync(() => void carry.forgotten?.push(threadId)), }), @@ -261,7 +296,11 @@ const link = (access: PeerLink["access"]): PeerLink => ({ }); /** Packs `repos.a`'s thread the way the computer it leaves does. */ -const pack = (repos: ReturnType, nativeSession?: NativeSessionExport | null) => +const pack = ( + repos: ReturnType, + nativeSession?: NativeSessionExport | null, + state?: PeerMoveThreadState, +) => Effect.gen(function* () { const git = yield* GitVcsDriver.GitVcsDriver; const checkout = yield* inspectMoveCheckout(git, repos.a, "origin"); @@ -283,6 +322,7 @@ const pack = (repos: ReturnType, nativeSession?: NativeSession }, agent, nativeSession, + state, }); return { manifest, payload: fs.readFileSync(movePayloadPath(dir)), checkout }; }); @@ -926,6 +966,362 @@ describe("LinkMoves, a clean thread", () => { ); }); +describe("LinkMoves, what a thread had going (Part 3e)", () => { + const at = "2026-10-22T10:00:00.000Z"; + const carried = (extra?: Partial): PeerMoveThreadState => ({ + goal: { + objective: "Make the suite pass", + status: "active", + tokenBudget: 5_000, + tokensUsed: 1_200, + timeUsedSeconds: 60, + createdAt: at, + updatedAt: at, + pickUp: true, + }, + checkBacks: [ + { + scheduledFor: "2030-01-01T10:00:00.000Z", + recurring: false, + exact: true, + prompt: "Look at CI on #212", + durable: false, + }, + ], + pullRequests: { + autoFix: true, + autoMerge: null, + linked: [ + { number: 212, url: "https://example.com/repo/pull/212", autoFix: true, autoMerge: null }, + ], + }, + queuedFollowUps: [ + { + messageId: MessageId.make("q-1"), + text: "and then this", + attachments: [], + interactionMode: "default", + createdAt: at, + }, + ], + proposedPlans: [ + { + id: "plan-1", + turnId: TurnId.make("turn-1"), + planMarkdown: "1. Fix it", + implementedAt: null, + implementationThreadId: ThreadId.make("thread-a"), + dismissedAt: null, + createdAt: at, + updatedAt: at, + }, + ], + plansLeftBehind: 3, + ...extra, + }); + /** The moved thread as it reads here: the queue its import wrote, and no session. */ + const landedShell = (dispatched: OrchestrationCommand[]) => () => { + const imported = dispatched.find((entry) => entry.type === "thread.import"); + if (imported?.type !== "thread.import") return undefined; + const head = imported.arrival?.message?.messageId ?? imported.queuedFollowUps?.[0]?.messageId; + return { + queuedFollowUps: head === undefined ? [] : [{ messageId: head }], + session: null, + } as unknown as OrchestrationThreadShell; + }; + const importOf = (dispatched: OrchestrationCommand[]) => { + const command = dispatched.find((entry) => entry.type === "thread.import"); + assert(command?.type === "thread.import"); + return command; + }; + const sends = (dispatched: OrchestrationCommand[]) => + dispatched.filter((entry) => entry.type === "thread.follow-up.send-queued"); + + it.live("lands with its goal, pull requests, plans and queue, and sends its arrival once", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* pack(repos, null, carried()); + const state = yield* deliver(manifest, payload); + assert.equal(state.status, "committed", state.reason); + const command = importOf(dispatched); + // Working, it is picked up here, with its budget as it was. + assert.deepInclude(command.goal, { status: "active", tokenBudget: 5_000, tokensUsed: 1_200 }); + assert.deepEqual(command.pullRequests, { + autoFix: true, + autoMerge: null, + linked: [ + { number: 212, url: "https://example.com/repo/pull/212", autoFix: true, autoMerge: null }, + ], + }); + // This computer's ids, the plan pointing at the thread it is now. + assert.notEqual(command.queuedFollowUps?.[0]?.messageId, "q-1"); + assert.equal(command.queuedFollowUps?.[0]?.runtimeMode, "auto-accept-edits"); + assert.notEqual(command.proposedPlans?.[0]?.id, "plan-1"); + assert.equal(command.proposedPlans?.[0]?.implementationThreadId, command.threadId); + const message = command.arrival?.message?.text ?? ""; + assert.include(message, "This thread moved from Windows PC to Mac mini"); + assert.include(message, "Your goal is still on: Make the suite pass. Carry on with it."); + // This computer's agent (a Codex) can't set check-backs: told once. + assert.include(message, "you can't set them here"); + assert.include(message, "Look at CI on #212"); + assert.deepEqual(command.arrival?.brought, [ + "its goal", + "auto-fix for #212", + "1 queued message", + "its plan", + ]); + assert.include(command.arrival?.left.join("\n"), "can't set them"); + assert.include(command.arrival?.left.join("\n"), "3 older plans stayed on Windows PC."); + // One send: the arrival message, by the move's own command id. + assert.deepEqual( + sends(dispatched).map((entry) => + entry.type === "thread.follow-up.send-queued" ? entry.messageId : null, + ), + [command.arrival?.message?.messageId ?? null], + ); + + // A restart before the arrival was recorded sends it then. + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE link_moves SET stage = 'applied'`; + dispatched.splice(0, dispatched.length, command); + const moves = yield* LinkMoves; + yield* Effect.scoped(moves.startReactor().pipe(Effect.andThen(Effect.sleep("300 millis")))); + assert.lengthOf(sends(dispatched), 1); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + shell: landedShell(dispatched), + }), + ), + ); + }); + + it.live( + "a token budget going to Claude arrives paused, and Claude sets its check-backs again", + () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* pack(repos, null, carried()); + assert.equal((yield* deliver(manifest, payload)).status, "committed"); + const command = importOf(dispatched); + assert.deepInclude(command.goal, { status: "paused", tokenBudget: null }); + assert.include( + command.arrival?.left.join("\n"), + "Its goal came paused: the agent here can't keep its token budget. Resume runs it without one.", + ); + const message = command.arrival?.message?.text ?? ""; + assert.notInclude(message, "Your goal is still on"); + assert.include(message, "Run CronList, then set again the ones you still need"); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + capabilities: { threadGoalBudget: "unsupported", checkBacks: "supported" }, + shell: landedShell(dispatched), + }), + ), + ); + }, + ); + + it.live("a goal that finished arrives finished, and nobody is told to carry on with it", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const finished = carried({ checkBacks: [], queuedFollowUps: [] }); + const { manifest, payload } = yield* pack(repos, null, { + ...finished, + goal: { ...finished.goal!, status: "complete", pickUp: true }, + }); + assert.equal((yield* deliver(manifest, payload)).status, "committed"); + const command = importOf(dispatched); + assert.equal(command.goal?.status, "complete"); + assert.isUndefined(command.arrival?.message); + assert.lengthOf(sends(dispatched), 0); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + shell: landedShell(dispatched), + }), + ), + ); + }); + + it.live("a branch renamed here arrives with its switches off, and says why", () => { + const repos = makeRepos(); + // This computer already has a branch of that name, elsewhere. + run(repos.b, "branch", "feature/move-me"); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* pack(repos, null, carried()); + assert.equal((yield* deliver(manifest, payload)).status, "committed"); + const command = importOf(dispatched); + assert.equal(command.branch, "feature/move-me-from-windows-pc"); + assert.deepEqual(command.pullRequests, { + autoFix: false, + autoMerge: null, + linked: [ + { + number: 212, + url: "https://example.com/repo/pull/212", + autoFix: false, + autoMerge: null, + }, + ], + }); + assert.include( + command.arrival?.left.join("\n"), + "Auto-fix is off here: this computer already has a branch named `feature/move-me`, so pushes from this thread wouldn't reach pull request #212.", + ); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + shell: landedShell(dispatched), + }), + ), + ); + }); + + it.live("the branch made here tracks the one it tracked there, when the remote has it", () => { + const repos = makeRepos(); + run(repos.a, "push", "--quiet", "-u", "origin", "feature/move-me"); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* pack(repos); + assert(!("workspace" in manifest)); + assert.equal(manifest.git.upstreamBranch, "feature/move-me"); + assert.equal((yield* deliver(manifest, payload)).status, "committed"); + const command = importOf(dispatched); + assert.equal( + run(command.worktreePath!, "rev-parse", "--abbrev-ref", "feature/move-me@{upstream}"), + "origin/feature/move-me", + ); + }).pipe(Effect.provide(testLayer(repos, dispatched))); + }); +}); + +describe("LinkMoves, a General Chats thread", () => { + /** A general chat's folder on the computer it leaves, with files in it. */ + const chatFolder = (root: string) => { + const folder = path.join(root, "general-a", "threads", "thread-a"); + fs.mkdirSync(path.join(folder, "data"), { recursive: true }); + fs.writeFileSync(path.join(folder, "notes.md"), "# Ideas\n"); + fs.writeFileSync(path.join(folder, "data", "out.csv"), "a,b\n1,2\n"); + fs.writeFileSync(path.join(folder, "run.sh"), "#!/bin/sh\necho hi\n", { mode: 0o755 }); + return folder; + }; + const packChat = (root: string) => + Effect.gen(function* () { + const dir = path.join(root, "export-chat"); + const manifest = yield* writeScratchExport({ + dir, + folder: chatFolder(root), + attachmentsDir: path.join(root, "attachments"), + thread: movingThread(), + source: { + environmentId: EnvironmentId.make("environment-windows"), + environmentLabel: "Windows PC", + threadId: ThreadId.make("thread-a"), + }, + agent, + }); + return { manifest, payload: fs.readFileSync(movePayloadPath(dir)) }; + }); + const landedFolder = (root: string) => + path.join( + root, + "general-b", + "threads", + linkMoveThreadId(linkMoveKey("device-windows", TRANSFER)), + ); + + it.live("lands in General chats with every file of its folder", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* packChat(repos.root); + assert.deepEqual(manifest.summary, { messageCount: 2, files: 3 }); + const state = yield* deliver(manifest, payload); + assert.equal(state.status, "committed", state.reason); + const command = dispatched.find((entry) => entry.type === "thread.import"); + assert(command?.type === "thread.import"); + assert.equal(command.projectId, GENERAL_CHATS_PROJECT_ID); + assert.isNull(command.worktreePath); + assert.isNull(command.branch); + const folder = landedFolder(repos.root); + assert.deepEqual(filesUnder(folder), ["data/out.csv", "notes.md", "run.sh"]); + assert.equal(fs.readFileSync(path.join(folder, "notes.md"), "utf8"), "# Ideas\n"); + if (process.platform !== "win32") { + assert.notEqual(fs.statSync(path.join(folder, "run.sh")).mode & 0o111, 0); + } + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + generalChatsRoot: path.join(repos.root, "general-b"), + }), + ), + ); + }); + + it.live("a folder already there stops the move, and is left as it was", () => { + const repos = makeRepos(); + const folder = landedFolder(repos.root); + fs.mkdirSync(folder, { recursive: true }); + fs.writeFileSync(path.join(folder, "theirs.txt"), "not the move's\n"); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* packChat(repos.root); + const state = yield* deliver(manifest, payload); + assert.equal(state.status, "aborted"); + assert.include(state.reason, "already has a folder"); + assert.deepEqual(filesUnder(folder), ["theirs.txt"]); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + generalChatsRoot: path.join(repos.root, "general-b"), + }), + ), + ); + }); + + it.live("a move dropped after its files arrived takes its own folder away", () => { + const repos = makeRepos(); + const dispatched: OrchestrationCommand[] = []; + return Effect.gen(function* () { + const { manifest, payload } = yield* packChat(repos.root); + const state = yield* deliver(manifest, payload); + assert.equal(state.status, "aborted"); + const folder = landedFolder(repos.root); + for (let tries = 0; tries < 100 && fs.existsSync(folder); tries += 1) { + yield* Effect.sleep("20 millis"); + } + assert.isFalse(fs.existsSync(folder)); + }).pipe( + Effect.provide( + testLayer(repos, dispatched, "allowed", () => false, [], { + home: os.tmpdir(), + adopted: [], + failImport: true, + generalChatsRoot: path.join(repos.root, "general-b"), + }), + ), + ); + }); +}); + describe("what a move may write here", () => { it("measures a binary change by the file it makes, delta or literal", () => { const repos = makeRepos(); diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index f1898db41..d3f611805 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -34,19 +34,35 @@ import { type ComputerLinkPendingRequest, ComputerLinkError, EventId, + GENERAL_CHATS_PROJECT_ID, + isScratchMoveManifest, type LinksRespondRequestInput, MessageId, + type OrchestrationProposedPlan, + type OrchestrationQueuedFollowUp, + type OrchestrationThreadGoal, + type OrchestrationThreadLinkedPullRequest, type PeerMoveChunkInput, type PeerMoveInput, type PeerMoveManifest, type PeerMovePart, type PeerMovePrepareInput, type PeerMoveAbortCode, + type PeerMoveReadinessInput, + type PeerMoveReadinessResult, type PeerMoveRefusalCode, type PeerMoveState, + type PeerMoveThreadState, type ProviderInstanceId, + type ProviderInteractionMode, + type PullRequestMergeMethod, type RuntimeMode, PEER_MOVE_CHUNK_MAX_BYTES, + PEER_MOVE_STATE_MAX_BYTES, + PEER_MOVE_STATE_MAX_CHECK_BACKS, + PEER_MOVE_STATE_MAX_PLANS, + PEER_MOVE_STATE_MAX_PULL_REQUESTS, + PEER_MOVE_STATE_MAX_QUEUED, PeerRpcError, ThreadId, type ThreadImportMessage, @@ -72,8 +88,11 @@ import { ServerConfig } from "../config.ts"; import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; import { receivedPathRefusal, writeReceivedFile } from "../fs/receivedFiles.ts"; import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts"; +import { arrivalMessageText } from "../moves/arrivalMessage.ts"; import { MOVE_MAX_BYTES } from "../moves/moveExport.ts"; import { derivedUuid } from "../orchestration/childRequestIds.ts"; +import { generalChatThreadScratchCwd } from "../orchestration/generalChats.ts"; + import { clampLaunchToCeiling } from "../orchestration/childThreadDecisions.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; @@ -82,6 +101,7 @@ import { discardSessionFiles, releaseSessionFiles } from "../provider/nativeSess import { ProviderService } from "../provider/Services/ProviderService.ts"; import { RepositoryIdentityResolver } from "../project/Services/RepositoryIdentityResolver.ts"; import { RelayDeviceRepository } from "../relay/RelayDeviceRepository.ts"; +import { GitHubCli } from "../sourceControl/GitHubCli.ts"; import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; import { makeKeyedLock } from "./keyedLock.ts"; import { LinkMoveRepository, type LinkMoveRow } from "./LinkMoveRepository.ts"; @@ -154,6 +174,14 @@ export interface LinkMovesShape { readonly pendingChanges: Stream.Stream; /** An inbound link was removed: its unfinished moves are dropped. */ readonly dropLink: (deviceId: string) => Effect.Effect; + /** + * Whether a project's pull requests can be watched here (`peer.move.readiness`, + * docs/design/fleet.md, Part 3e, (c)): asked before a thread with switches on moves. + */ + readonly readiness: ( + link: PeerLink, + input: PeerMoveReadinessInput, + ) => Effect.Effect; /** Settle what the previous process left, and sweep hourly. */ readonly startReactor: () => Effect.Effect; } @@ -200,9 +228,14 @@ export function moveManifestRefusal(manifest: PeerMoveManifest): string | null { if (next !== manifest.totalBytes) return "its parts don't add up"; const count = (kind: PeerMovePart["kind"]) => manifest.parts.filter((part) => part.kind === kind).length; - if (count("bundle") > 1 || count("diff") > 1) return "it has more than one bundle or diff"; - if ((count("bundle") === 1) !== (manifest.git.baseSha !== null)) { - return "its commits don't match its base"; + if (isScratchMoveManifest(manifest)) { + // A general chat's folder is its files alone. + if (count("bundle") > 0 || count("diff") > 0) return "a general chat carries no commits"; + } else { + if (count("bundle") > 1 || count("diff") > 1) return "it has more than one bundle or diff"; + if ((count("bundle") === 1) !== (manifest.git.baseSha !== null)) { + return "its commits don't match its base"; + } } const seen = new Set(); for (const part of manifest.parts) { @@ -224,9 +257,46 @@ export function moveManifestRefusal(manifest: PeerMoveManifest): string | null { if (count("session") > 0 !== (manifest.session !== undefined)) { return "its session doesn't match its files"; } + return moveStateRefusal(manifest.thread.state); +} + +/** Why what a moved thread had going can't be taken, or null: within its bounds. */ +function moveStateRefusal(state: PeerMoveThreadState | undefined): string | null { + if (state === undefined) return null; + if (JSON.stringify(state).length > PEER_MOVE_STATE_MAX_BYTES) { + return "what it had going is too big"; + } + if ((state.queuedFollowUps ?? []).length > PEER_MOVE_STATE_MAX_QUEUED) { + return "it has too many queued messages"; + } + if ((state.checkBacks ?? []).length > PEER_MOVE_STATE_MAX_CHECK_BACKS) { + return "it has too many check-backs"; + } + if ((state.proposedPlans ?? []).length > PEER_MOVE_STATE_MAX_PLANS) { + return "it has too many plans"; + } + if ((state.pullRequests?.linked ?? []).length > PEER_MOVE_STATE_MAX_PULL_REQUESTS) { + return "it has too many pull requests"; + } return null; } +/** The git half of a move's manifest; a general chat has none. */ +const gitOf = (manifest: PeerMoveManifest) => + isScratchMoveManifest(manifest) ? null : manifest.git; + +/** What the allow card says a move brings: a general chat's files count as new files. */ +function moveSummaryOf(manifest: PeerMoveManifest) { + return isScratchMoveManifest(manifest) + ? { branch: null, trackedFiles: 0, untrackedFiles: manifest.summary.files, unpushedCommits: 0 } + : { + branch: manifest.git.branch, + trackedFiles: manifest.summary.trackedFiles, + untrackedFiles: manifest.summary.untrackedFiles, + unpushedCommits: manifest.summary.unpushedCommits, + }; +} + const BASE85 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"; @@ -319,6 +389,9 @@ const make = Effect.gen(function* () { const setupScripts = yield* ProjectSetupScriptRunner; const environment = yield* ServerEnvironment; const providers = yield* ProviderService; + // GitHub's sign-in, for the pull request switches a move brings; none in a + // server built without it (tests), which then can't tell. + const gitHubCli = yield* Effect.serviceOption(GitHubCli); // Read at each use: the computer can be renamed while this runs. const ownLabel = environment.currentLabel; const pendingHub = yield* PubSub.sliding(1); @@ -429,6 +502,18 @@ const make = Effect.gen(function* () { /** The project here a move lands in, and the remote it fetches from. */ const landing = (manifest: PeerMoveManifest) => Effect.gen(function* () { + // A general chat lands in this computer's General chats. + if (isScratchMoveManifest(manifest)) { + const catalog = yield* snapshots + .getProjectCatalog() + .pipe(Effect.orElseSucceed(() => ({ projects: [] as const }))); + const project = catalog.projects.find( + (entry) => entry.id === GENERAL_CHATS_PROJECT_ID && entry.deletedAt === null, + ); + return project === undefined + ? null + : { project, root: project.workspaceRoot, remoteName: "" }; + } const project = yield* requests.projectForKey( manifest.project.canonicalKey, manifest.project.subdirectory, @@ -480,6 +565,29 @@ const make = Effect.gen(function* () { Effect.as(true), Effect.orElseSucceed(() => false), )); + // A general chat made only its folder. + if (isScratchMoveManifest(row.manifest)) { + const folder = row.worktreePath; + if (folder !== null) { + const ours = yield* ownsScratchFolder(row, folder); + if (ours === null) clean = false; + else if (ours) { + yield* Effect.promise(() => + NodeFs.rm(folder, { recursive: true, force: true }).catch(() => undefined), + ); + if ((yield* pathState(folder)) !== false) clean = false; + } + } + if (!clean) return; + yield* moves + .markCleaned({ + linkDeviceId: row.linkDeviceId, + transferId: row.transferId, + now: yield* nowIso, + }) + .pipe(Effect.ignore); + return; + } // The repository recorded when the import began (nothing was made in // git before that). One deleted since took its refs and worktree list // with it; one that is there but can't be read, or can't be told @@ -525,7 +633,7 @@ const make = Effect.gen(function* () { if ( row.branch !== null && at.ok && - at.out === row.manifest.git.headSha && + at.out === gitOf(row.manifest)?.headSha && (yield* ownsBranch(repo, row.branch, row)) ) { const deleted = yield* runGit(repo, ["branch", "-D", row.branch]); @@ -549,6 +657,30 @@ const make = Effect.gen(function* () { .pipe(Effect.ignore); }); + /** Where a general chat moved here keeps its files: its own folder in General chats. */ + const scratchFolderOf = (root: string, row: Pick) => + generalChatThreadScratchCwd(root, row.threadId, NodePath); + + /** + * Whether `folder` is the one this general chat's move made, so clean-up + * may remove it: it is the folder named from this move's thread, and no + * thread with that id exists here (only that thread's sessions could have + * made it otherwise). Null when that can't be read. + */ + const ownsScratchFolder = (row: LinkMoveRow, folder: string) => + Effect.gen(function* () { + const land = yield* landing(row.manifest); + const named = + land !== null + ? folder === scratchFolderOf(land.root, row) + : NodePath.basename(folder) === row.threadId && + NodePath.basename(NodePath.dirname(folder)) === "threads"; + if (!named) return false; + const thread = yield* threadRows.getById({ threadId: row.threadId }).pipe(Effect.option); + if (Option.isNone(thread)) return null; + return Option.isNone(thread.value); + }); + /** Whether `path` is there: false only when it's confirmed gone, null when that can't be told. */ const pathState = (path: string) => Effect.promise(() => @@ -916,7 +1048,8 @@ const make = Effect.gen(function* () { */ const settleLanded = (row: LinkMoveRow) => Effect.gen(function* () { - if (row.worktreePath !== null) { + // A general chat's folder gets no setup script: it isn't a project's worktree. + if (row.worktreePath !== null && !isScratchMoveManifest(row.manifest)) { const land = yield* landing(row.manifest); if (land !== null) { yield* setupScripts @@ -969,6 +1102,7 @@ const make = Effect.gen(function* () { yield* settleLanded(row).pipe( Effect.mapError(() => peerFailure(`${ownLabel()} couldn't record that.`)), ); + yield* arrive(row); return stateOf({ ...row, status: "committed" }); } const why = reason ?? "The move was cancelled."; @@ -1047,7 +1181,9 @@ const make = Effect.gen(function* () { yield* setStage(row, { repoRoot: top.out }); yield* runGit(land.root, ["fetch", "--quiet", land.remoteName], GIT_FETCH_TIMEOUT_MS); const bundle = row.manifest.parts.find((part) => part.kind === "bundle"); - const { headSha, baseSha } = row.manifest.git; + const moved = gitOf(row.manifest); + if (moved === null) return yield* stop(`${ownLabel()} lost track of the move.`); + const { headSha, baseSha } = moved; if (bundle !== undefined && baseSha === null) { return yield* stop(`${ownLabel()} can't take commits that start from nothing.`); } @@ -1151,7 +1287,9 @@ const make = Effect.gen(function* () { */ const expansionBytes = (row: LinkMoveRow, root: string) => Effect.gen(function* () { - const { headSha, baseSha } = row.manifest.git; + const moved = gitOf(row.manifest); + if (moved === null) return null; + const { headSha, baseSha } = moved; const committed = baseSha === null || !row.manifest.parts.some((part) => part.kind === "bundle") ? 0 @@ -1172,7 +1310,7 @@ const make = Effect.gen(function* () { /** The branch name the move takes here: its own, else one marked with where it came from. */ const pickBranch = (root: string, row: LinkMoveRow) => Effect.gen(function* () { - const source = row.manifest.git.branch; + const source = gitOf(row.manifest)?.branch ?? null; const from = row.manifest.source.environmentLabel .toLowerCase() .replace(/[^a-z0-9]+/g, "-") @@ -1209,7 +1347,9 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const land = yield* landing(row.manifest); if (land === null) return yield* stop(`${ownLabel()} doesn't have this project anymore.`); - const { headSha } = row.manifest.git; + const moved = gitOf(row.manifest); + if (moved === null) return yield* stop(`${ownLabel()} lost track of the move.`); + const { headSha } = moved; const branch = row.branch ?? (yield* pickBranch(land.root, row)); const path = row.worktreePath ?? @@ -1239,6 +1379,7 @@ const make = Effect.gen(function* () { } const head = yield* runGit(path, ["rev-parse", "HEAD"]); if (head.ok && head.out === headSha) { + if (row.branch !== null) yield* trackUpstream(land, row, row.branch); yield* setStage(row, { stage: "worktree" }); return; } @@ -1277,9 +1418,41 @@ const make = Effect.gen(function* () { return yield* stop(`${ownLabel()}'s worktree for it isn't at the moved commit.`); } yield* runGit(land.root, ["update-ref", "-d", tempRef(row)]); + yield* trackUpstream(land, row, name); yield* setStage(row, { stage: "worktree" }); }); + /** + * The branch made here tracks the branch it tracked there, when the remote + * has it (docs/design/fleet.md, Part 3e, (c)): the thread's own pull + * request is found by it, and a merge waits for commits not pushed to it. + * For every move, whatever its switches. Best effort: a branch left without + * one says so at the commit (`upstreamOf`). + */ + const trackUpstream = ( + land: { readonly root: string; readonly remoteName: string }, + row: LinkMoveRow, + branch: string, + ) => + Effect.gen(function* () { + const upstream = gitOf(row.manifest)?.upstreamBranch; + if (upstream === undefined || land.remoteName.length === 0) return; + const remoteRef = `refs/remotes/${land.remoteName}/${upstream}`; + const there = yield* runGit(land.root, ["rev-parse", "--verify", "--quiet", remoteRef]); + if (!there.ok) return; + yield* runGit(land.root, ["config", `branch.${branch}.remote`, land.remoteName]); + yield* runGit(land.root, ["config", `branch.${branch}.merge`, `refs/heads/${upstream}`]); + }); + + /** The upstream the moved thread's branch tracks here (`/`), or null. */ + const upstreamOf = (root: string, branch: string) => + runGit(root, [ + "rev-parse", + "--abbrev-ref", + "--symbolic-full-name", + `${branch}@{upstream}`, + ]).pipe(Effect.map((result) => (result.ok && result.out.length > 0 ? result.out : null))); + /** Writes one new file, refusing any parent that is a symbolic link. */ const writeNewFile = (root: string, part: PeerMovePart, bytes: Buffer) => Effect.tryPromise(() => @@ -1301,7 +1474,9 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const path = row.worktreePath; if (path === null) return yield* stop(`${ownLabel()} lost track of the move's worktree.`); - const { headSha } = row.manifest.git; + const moved = gitOf(row.manifest); + if (moved === null) return yield* stop(`${ownLabel()} lost track of the move.`); + const { headSha } = moved; const status = yield* runGit(path, ["status", "--porcelain"]); if (status.out.length > 0) { // Ours, uncommitted, never handed to a thread: back to the moved commit. @@ -1349,6 +1524,82 @@ const make = Effect.gen(function* () { yield* setStage(row, { stage: "applied" }); }); + /** + * A general chat's own folder in General chats here (docs/design/fleet.md, + * Part 3e, (d)), named from the move's thread: recorded before it is made, + * then made with an exclusive mkdir, so a folder already there that holds + * anything stops the move rather than being written into. + */ + const folderStage = (row: LinkMoveRow) => + Effect.gen(function* () { + const land = yield* landing(row.manifest); + if (land === null) return yield* stop(`${ownLabel()} has no General chats to put it in.`); + const folder = row.worktreePath ?? scratchFolderOf(land.root, row); + const firstTime = row.worktreePath === null; + // One there with anything in it before this move picked it isn't its + // own: the move stops before it is on record, so clean-up never touches it. + if (firstTime) { + const held = yield* Effect.promise(() => + NodeFs.readdir(folder).then( + (entries) => entries.length > 0, + (error: NodeJS.ErrnoException) => error.code !== "ENOENT", + ), + ); + if (held) return yield* stop(`${ownLabel()} already has a folder at ${folder}.`); + yield* setStage(row, { worktreePath: folder }); + } + const made = yield* Effect.tryPromise(async () => { + await NodeFs.mkdir(NodePath.dirname(folder), { recursive: true }); + try { + await NodeFs.mkdir(folder); + return "made" as const; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + return (await NodeFs.readdir(folder)).length === 0 + ? ("empty" as const) + : ("full" as const); + } + }).pipe( + Effect.mapError( + () => new ImportStop({ reason: `${ownLabel()} couldn't make a folder for this chat.` }), + ), + ); + // One there before this move picked it isn't its own. + if (made === "full" && firstTime) { + return yield* stop(`${ownLabel()} already has a folder at ${folder}.`); + } + yield* setStage(row, { stage: "folder" }); + }); + + /** A general chat's files, into its folder. A crashed write starts again in an emptied folder. */ + const scratchApplyStage = (row: LinkMoveRow) => + Effect.gen(function* () { + const folder = row.worktreePath; + if (folder === null) return yield* stop(`${ownLabel()} lost track of the chat's folder.`); + const entries = yield* Effect.tryPromise(() => NodeFs.readdir(folder)).pipe( + Effect.mapError(() => new ImportStop({ reason: `${ownLabel()} lost the chat's folder.` })), + ); + if (entries.length > 0) { + if ((yield* ownsScratchFolder(row, folder)) !== true) { + return yield* stop(`A thread on ${ownLabel()} is using that folder.`); + } + yield* Effect.tryPromise(async () => { + await NodeFs.rm(folder, { recursive: true, force: true }); + await NodeFs.mkdir(folder); + }).pipe( + Effect.mapError( + () => new ImportStop({ reason: `${ownLabel()} couldn't empty the chat's folder.` }), + ), + ); + } + for (const part of row.manifest.parts.filter((entry) => entry.kind === "file")) { + const refusal = movePathRefusal(part.path ?? ""); + if (refusal !== null) return yield* stop(`${ownLabel()} can't take it: ${refusal}.`); + yield* writeNewFile(folder, part, yield* partBytes(row, part)); + } + yield* setStage(row, { stage: "applied" }); + }); + /** The new attachment a moved one becomes here: an id of this thread, written beside the others. */ const importAttachments = (row: LinkMoveRow) => Effect.gen(function* () { @@ -1360,7 +1611,12 @@ const make = Effect.gen(function* () { .filter((part) => part.kind === "attachment") .map((part) => [part.attachmentId!, part] as const), ); - for (const message of row.manifest.thread.messages) { + // The history's, and the queued messages' (docs/design/fleet.md, Part 3e, (e)). + const carriers = [ + ...row.manifest.thread.messages, + ...(row.manifest.thread.state?.queuedFollowUps ?? []), + ]; + for (const message of carriers) { for (const attachment of message.attachments ?? []) { if (remapped.has(attachment.id)) continue; const id = `${segment}-${derivedUuid("link-move-attachment", row.transferKey, attachment.id)}`; @@ -1567,6 +1823,20 @@ const make = Effect.gen(function* () { ? yield* carrySession(row, agent.selection.instanceId, capped.runtimeMode) : false; const now = yield* nowIso; + const fromLabel = Option.isSome(device) + ? device.value.label + : row.manifest.source.environmentLabel; + const scratch = isScratchMoveManifest(row.manifest); + const state = yield* importedState({ + row, + root: land.root, + instanceId: agent.selection.instanceId, + runtimeMode: capped.runtimeMode, + interactionMode: capped.interactionMode, + attachments, + fromLabel, + now, + }); const dispatched = yield* engine .dispatch({ type: "thread.import", @@ -1577,19 +1847,19 @@ const make = Effect.gen(function* () { modelSelection: agent.selection, runtimeMode: capped.runtimeMode, interactionMode: capped.interactionMode, - branch: row.branch, - worktreePath: row.worktreePath, + // A general chat works in its folder as every general chat does: by its id. + branch: scratch ? null : row.branch, + worktreePath: scratch ? null : row.worktreePath, movedFrom: { environmentId: row.manifest.source.environmentId, - label: Option.isSome(device) - ? device.value.label - : row.manifest.source.environmentLabel, + label: fromLabel, threadId: row.manifest.source.threadId, movedAt: now, }, messages, activities, ...(carried ? { nativeSession: "carried" as const } : {}), + ...state, createdAt: now, }) .pipe(Effect.uninterruptible, Effect.exit); @@ -1600,6 +1870,319 @@ const make = Effect.gen(function* () { const carriedFiles = yield* readCarriedRecord(row); if (carriedFiles !== null) yield* releaseSessionFiles(carriedFiles, row.transferKey); yield* settleLanded(row).pipe(Effect.ignore); + yield* arrive(row); + }); + + /** The ids a move's import gives the queue it writes: its arrival message, then the user's. */ + const arrivalMessageId = (row: Pick) => + MessageId.make(derivedUuid("link-move-arrival", row.transferKey)); + const queuedMessageId = (row: Pick, id: string) => + MessageId.make(derivedUuid("link-move-queued", row.transferKey, id)); + + /** + * What a moved thread had going, as it lands here (docs/design/fleet.md, + * Part 3e), for the agent picked here: its goal as it arrives, its pull + * request switches (off, with why, when its branch had to be renamed), its + * plans and queue with this computer's ids, and the arrival: the message + * its agent is told, and the "Moved here" line's two lists. + */ + const importedState = (input: { + readonly row: LinkMoveRow; + readonly root: string; + readonly instanceId: ProviderInstanceId; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly attachments: ReadonlyMap; + readonly fromLabel: string; + readonly now: string; + }) => + Effect.gen(function* () { + const { row, now } = input; + const state = row.manifest.thread.state; + if (state === undefined) return {}; + const key = row.transferKey; + const capabilities = yield* providers + .getCapabilities(input.instanceId) + .pipe(Effect.orElseSucceed(() => null)); + const keepsGoals = capabilities?.threadGoals === "supported"; + const keepsBudgets = keepsGoals && capabilities?.threadGoalBudget !== "unsupported"; + const setsCheckBacks = capabilities?.checkBacks === "supported"; + const brought: string[] = []; + const left: string[] = []; + + // (a) The goal. + let goal: OrchestrationThreadGoal | undefined; + let goalToTell: { readonly objective: string } | null = null; + const carriedGoal = state.goal; + if (carriedGoal !== undefined) { + // Only a goal still working or paused is picked up; one that finished stays finished. + const pickUp = + carriedGoal.pickUp && + (carriedGoal.status === "active" || carriedGoal.status === "paused"); + const { pickUp: _pickUp, ...record } = carriedGoal; + if (!keepsGoals) { + left.push( + `Its goal didn't come along: the agent here can't keep goals. It was: ${carriedGoal.objective}`, + ); + if (pickUp) goalToTell = { objective: carriedGoal.objective }; + } else if ( + carriedGoal.tokenBudget !== null && + !keepsBudgets && + carriedGoal.status !== "complete" + ) { + // The agent here refuses a budget: the goal waits, and Resume runs it without one. + goal = { ...record, threadId: row.threadId, status: "paused", tokenBudget: null }; + left.push( + "Its goal came paused: the agent here can't keep its token budget. Resume runs it without one.", + ); + } else { + const status = pickUp + ? "active" + : carriedGoal.status === "active" || + carriedGoal.status === "paused" || + carriedGoal.status === "usageLimited" + ? "paused" + : carriedGoal.status; + goal = { ...record, threadId: row.threadId, status }; + if (pickUp) goalToTell = { objective: carriedGoal.objective }; + if (carriedGoal.status !== "complete") { + brought.push(status === "paused" ? "its goal, paused" : "its goal"); + } + } + } + + // (b) Check-backs: the agent sets them again (or is told once). + const checkBacks = state.checkBacks ?? []; + if (checkBacks.length > 0) { + if (setsCheckBacks) { + brought.push( + checkBacks.length === 1 + ? "a check-back to set again" + : `${checkBacks.length} check-backs to set again`, + ); + } else { + left.push( + "Its check-backs didn't come along: the agent here can't set them. It's told once what was planned.", + ); + } + } + + // (c) Pull request switches. + let pullRequests: + | { + readonly autoFix: boolean; + readonly autoMerge: PullRequestMergeMethod | null; + readonly linked: ReadonlyArray; + } + | undefined; + const carriedSwitches = state.pullRequests; + if (carriedSwitches !== undefined) { + const moved = gitOf(row.manifest); + const numbers = carriedSwitches.linked.map((entry) => `#${entry.number}`); + const which = + numbers.length > 0 ? `pull request ${numbers.join(", ")}` : "its pull request"; + // A branch renamed here doesn't push to the pull request; one that + // tracks nothing can't tell what isn't pushed yet. + const renamed = moved?.branch !== null && row.branch !== moved?.branch; + const untracked = + !renamed && + moved?.upstreamBranch !== undefined && + row.branch !== null && + (yield* upstreamOf(input.root, row.branch)) === null; + const off = renamed + ? `Auto-fix is off here: this computer already has a branch named \`${moved?.branch ?? ""}\`, so pushes from this thread wouldn't reach ${which}.` + : untracked + ? `Auto-fix is off here: this thread's branch couldn't track ${moved?.upstreamBranch ?? "its branch"} on this computer, so it can't tell what isn't pushed yet.` + : null; + const linked = carriedSwitches.linked.map((entry) => ({ + number: entry.number, + url: entry.url, + autoFix: off === null && entry.autoFix, + autoMerge: off === null ? entry.autoMerge : null, + })); + pullRequests = { + autoFix: off === null && carriedSwitches.autoFix, + autoMerge: off === null ? carriedSwitches.autoMerge : null, + linked, + }; + if (off !== null) { + left.push(off); + } else { + const ready = yield* gitHubReadiness(input.root); + const fixing = + carriedSwitches.autoFix || carriedSwitches.linked.some((entry) => entry.autoFix); + const merging = + carriedSwitches.autoMerge !== null || + carriedSwitches.linked.some((entry) => entry.autoMerge !== null); + const switches = + fixing && merging ? "auto-fix and auto-merge" : fixing ? "auto-fix" : "auto-merge"; + brought.push(`${switches} for ${which.replace(/^pull request /u, "")}`); + if (ready.gitHubReady === false) { + left.push( + "Auto-fix came along, but GitHub isn't signed in on this computer. Sign in and it starts.", + ); + } + } + } + + // (e) The user's queued messages, on the agent picked here, with this computer's ids. + const skipped = (state.queuedFollowUps ?? []).filter( + (entry) => (entry.skills ?? []).length > 0, + ).length; + const queuedFollowUps: OrchestrationQueuedFollowUp[] = (state.queuedFollowUps ?? []).map( + (entry) => ({ + messageId: queuedMessageId(row, entry.messageId), + text: entry.text, + attachments: entry.attachments.map( + (attachment) => input.attachments.get(attachment.id) ?? attachment, + ), + ...(entry.composer !== undefined ? { composer: entry.composer } : {}), + ...(entry.sentFrom !== undefined ? { sentFrom: entry.sentFrom } : {}), + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + createdAt: entry.createdAt, + }), + ); + if (queuedFollowUps.length > 0) { + brought.push( + queuedFollowUps.length === 1 + ? "1 queued message" + : `${queuedFollowUps.length} queued messages`, + ); + } + if (skipped > 0) { + left.push("Skills named in its queued messages stayed behind: send them again here."); + } + + // (f) Plans, with this computer's ids. + const key2 = (id: string) => derivedUuid("link-move-turn", key, id); + const proposedPlans: OrchestrationProposedPlan[] = (state.proposedPlans ?? []).map( + (plan) => ({ + id: derivedUuid("link-move-plan", key, plan.id), + turnId: plan.turnId === null ? null : TurnId.make(key2(plan.turnId)), + planMarkdown: plan.planMarkdown, + implementedAt: plan.implementedAt, + implementationThreadId: + plan.implementationThreadId === row.manifest.source.threadId ? row.threadId : null, + dismissedAt: plan.dismissedAt, + createdAt: plan.createdAt, + updatedAt: plan.updatedAt, + }), + ); + const newest = proposedPlans.at(-1); + if (newest !== undefined && newest.implementedAt === null && newest.dismissedAt === null) { + brought.push("its plan"); + } + const behind = state.plansLeftBehind ?? 0; + if (behind > 0) { + left.push( + behind === 1 + ? `1 older plan stayed on ${input.fromLabel}.` + : `${behind} older plans stayed on ${input.fromLabel}.`, + ); + } + + const text = arrivalMessageText({ + kind: "moved", + from: input.fromLabel, + to: ownLabel(), + goal: goalToTell, + checkBacks, + canSetCheckBacks: setsCheckBacks, + now, + }); + return { + ...(goal !== undefined ? { goal } : {}), + ...(pullRequests !== undefined ? { pullRequests } : {}), + ...(queuedFollowUps.length > 0 ? { queuedFollowUps } : {}), + ...(proposedPlans.length > 0 ? { proposedPlans } : {}), + arrival: { + ...(text !== null ? { message: { messageId: arrivalMessageId(row), text } } : {}), + brought, + left, + }, + }; + }); + + /** + * Whether GitHub is signed in here for the project at `root`: `gh auth + * status` answers. Absent: it couldn't tell (no `gh`, a read that failed). + */ + const gitHubReadiness = (root: string) => + Effect.gen(function* () { + if (Option.isNone(gitHubCli)) return {} satisfies PeerMoveReadinessResult; + const result = yield* gitHubCli.value + .execute({ cwd: root, args: ["auth", "status"], timeoutMs: 15_000 }) + .pipe(Effect.option); + return Option.isSome(result) + ? ({ gitHubReady: true } satisfies PeerMoveReadinessResult) + : ({ gitHubReady: false } satisfies PeerMoveReadinessResult); + }); + + const readiness: LinkMovesShape["readiness"] = (link, input) => + Effect.gen(function* () { + const authority = yield* requests.authority(link.deviceId); + if (!authority.ok) return yield* new PeerRpcError({ detail: authority.text }); + const project = yield* requests.projectForKey(input.canonicalKey); + if (project === undefined) return {}; + return yield* gitHubReadiness(project.workspaceRoot); + }); + + /** + * The arrival (docs/design/fleet.md, Part 3e, "One kick"): the head of the + * queue its import wrote is sent, with a command id from the move, then the + * move is recorded as arrived. The import's queue events send nothing, so + * this is the one send; a restart before it is recorded sends it then. A + * thread already at work here (its user sent something first) is left to + * its turn's end, which sends the queue as it always does. + */ + const arrive = (row: LinkMoveRow) => + Effect.gen(function* () { + const state = row.manifest.thread.state; + const ids = new Set([ + arrivalMessageId(row), + ...(state?.queuedFollowUps ?? []).map((entry) => queuedMessageId(row, entry.messageId)), + ]); + // Unreadable: left for the sweep to try again, never taken as gone. + const shell = yield* snapshots.getThreadShellById(row.threadId).pipe(Effect.option); + if (Option.isNone(shell)) return; + const thread = Option.getOrNull(shell.value); + const head = + state === undefined || thread === null + ? undefined + : (thread.queuedFollowUps ?? []).find((entry) => ids.has(entry.messageId)); + const busy = thread?.session?.status === "running" || thread?.session?.status === "starting"; + if (head !== undefined && !busy) { + const commandId = CommandId.make(`server:link-move:${row.transferKey}:arrive`); + const sent = yield* engine + .dispatch({ + type: "thread.follow-up.send-queued", + commandId, + threadId: row.threadId, + messageId: head.messageId, + createdAt: yield* nowIso, + }) + .pipe(Effect.exit); + if (Exit.isFailure(sent)) { + // A refusal the engine recorded is an answer (the message went some + // other way); anything else is tried again by the sweep. + const receipt = yield* engine + .getCommandReceipt(commandId) + .pipe(Effect.orElseSucceed(() => Option.none())); + yield* Effect.logWarning("moved thread's arrival wasn't sent", { + threadId: row.threadId, + cause: sent.cause, + }); + if (Option.isNone(receipt)) return; + } + } + yield* moves + .markArrived({ + linkDeviceId: row.linkDeviceId, + transferId: row.transferId, + now: yield* nowIso, + }) + .pipe(Effect.ignore); }); /** @@ -1617,7 +2200,8 @@ const make = Effect.gen(function* () { Effect.gen(function* () { switch (row.stage) { case null: - yield* fetchStage(row); + // A general chat has a folder of its own, not a checkout. + yield* isScratchMoveManifest(row.manifest) ? folderStage(row) : fetchStage(row); return false; case "fetched": yield* worktreeStage(row); @@ -1625,9 +2209,14 @@ const make = Effect.gen(function* () { case "worktree": yield* applyStage(row); return false; + case "folder": + yield* scratchApplyStage(row); + return false; case "applied": yield* commitStage(row); return true; + case "arrived": + return true; } }), ); @@ -1807,10 +2396,7 @@ const make = Effect.gen(function* () { kind: "move", move: { messageCount: row.manifest.summary.messageCount, - branch: row.manifest.git.branch, - trackedFiles: row.manifest.summary.trackedFiles, - untrackedFiles: row.manifest.summary.untrackedFiles, - unpushedCommits: row.manifest.summary.unpushedCommits, + ...moveSummaryOf(row.manifest), ...(row.stagedApproval ? { bytesReceived: row.bytesReceived, totalBytes: row.manifest.totalBytes } : {}), @@ -1859,6 +2445,7 @@ const make = Effect.gen(function* () { if (row.status === "importing") { if (yield* importLanded(row)) { yield* settleLanded(row).pipe(Effect.ignore); + yield* arrive(row); } else { yield* runImport(row.linkDeviceId, row.transferId).pipe(Effect.forkIn(scope)); } @@ -1873,6 +2460,9 @@ const make = Effect.gen(function* () { ); } } + // Moves that landed before their arrival was sent (a restart between). + const unarrived = yield* moves.listUnarrived.pipe(Effect.orElseSucceed(() => [])); + for (const row of unarrived) yield* lock(row.transferKey)(arrive(row)); const owed = yield* moves.listCleanupOwed.pipe(Effect.orElseSucceed(() => [])); for (const row of owed) yield* lock(row.transferKey)(cleanUp(row)); const settled = yield* moves @@ -1905,6 +2495,7 @@ const make = Effect.gen(function* () { pending, pendingChanges: Stream.fromPubSub(pendingHub), dropLink, + readiness, startReactor, }); }); diff --git a/apps/server/src/links/peerRoute.ts b/apps/server/src/links/peerRoute.ts index b8707e8d1..e2621a23d 100644 --- a/apps/server/src/links/peerRoute.ts +++ b/apps/server/src/links/peerRoute.ts @@ -11,8 +11,10 @@ import { EnvironmentId, PeerRpcError, PeerRpcGroup, + type PeerAgent, type PeerDescriptor, type PeerCaller, + ProviderInstanceId, } from "@threadlines/contracts"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; @@ -34,6 +36,7 @@ import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSna import { RepositoryIdentityResolver } from "../project/Services/RepositoryIdentityResolver.ts"; import { resolveProjectPlace } from "../project/projectPlace.ts"; import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts"; +import { ProviderService } from "../provider/Services/ProviderService.ts"; import { RelayDeviceRepository } from "../relay/RelayDeviceRepository.ts"; import { RelayHost } from "../relay/RelayHost.ts"; import { ServerSettingsService } from "../serverSettings.ts"; @@ -69,6 +72,8 @@ export const makePeerRpcLayer = (input: { const relayHost = yield* RelayHost; const environment = yield* ServerEnvironment; const providers = yield* ProviderRegistry; + // What its agents keep of a moved thread; absent in a server built without it. + const providerService = yield* Effect.serviceOption(ProviderService); const settings = yield* ServerSettingsService; const snapshots = yield* ProjectionSnapshotQuery; const identities = yield* RepositoryIdentityResolver; @@ -178,6 +183,26 @@ export const makePeerRpcLayer = (input: { } } const defaultAgent = defaults?.newThreadModelSelection ?? null; + // What each agent keeps of a moved thread (docs/design/fleet.md, Part 3e). + const agents = yield* Effect.forEach( + listThreadAgents(all, { interactionMode: "default" }).agents, + (agent): Effect.Effect => + Option.isNone(providerService) + ? Effect.succeed(agent) + : providerService.value + .getCapabilities(ProviderInstanceId.make(agent.instanceId)) + .pipe( + Effect.map((capabilities) => ({ + ...agent, + threadGoals: capabilities.threadGoals === "supported", + goalBudget: + capabilities.threadGoals === "supported" && + capabilities.threadGoalBudget !== "unsupported", + checkBacks: capabilities.checkBacks === "supported", + })), + Effect.orElseSucceed(() => agent), + ), + ); return { environmentId: descriptor.environmentId, label: descriptor.label, @@ -186,7 +211,7 @@ export const makePeerRpcLayer = (input: { directRoutes: yield* relayHost.directRoutes(input.sessionId), access: link.access, maxRuntimeMode: link.maxRuntimeMode, - agents: listThreadAgents(all, { interactionMode: "default" }).agents, + agents, defaultAgent: defaultAgent === null ? null @@ -195,6 +220,8 @@ export const makePeerRpcLayer = (input: { moves: true, moveStagedApproval: true, moveNativeSession: true, + moveThreadState: true, + moveGeneralChats: true, threadFiling: true, outsideAgents: true, } satisfies PeerDescriptor; @@ -258,6 +285,8 @@ export const makePeerRpcLayer = (input: { guarded(Effect.flatMap(currentLink, (link) => linkMoves.status(link, payload))), "peer.move.abort": (payload) => guarded(Effect.flatMap(currentLink, (link) => linkMoves.abort(link, payload))), + "peer.move.readiness": (payload) => + guarded(Effect.flatMap(currentLink, (link) => linkMoves.readiness(link, payload))), // Outside agents connected on the asking computer (OutsideAgentLinks). "peer.outside.ask": (payload) => guarded(Effect.flatMap(outsideLink, ({ link, links }) => links.ask(link, payload))), diff --git a/apps/server/src/moves/MoveQueue.test.ts b/apps/server/src/moves/MoveQueue.test.ts index 1dc8634ee..ce1083f77 100644 --- a/apps/server/src/moves/MoveQueue.test.ts +++ b/apps/server/src/moves/MoveQueue.test.ts @@ -1,6 +1,7 @@ import { CommandId, EnvironmentId, + MessageId, ProjectId, ProviderInstanceId, ThreadId, @@ -10,9 +11,12 @@ import { type ModelSelection, type OrchestrationCommand, type OrchestrationEvent, + type OrchestrationQueuedFollowUp, type OrchestrationReadModel, type OrchestrationSession, + type OrchestrationThread, type ThreadMoveRequestId, + type ThreadMoveTakes, } from "@threadlines/contracts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -27,7 +31,7 @@ import { createEmptyReadModel, projectEvent } from "../orchestration/projector.t import type { ProviderStopConfirmation } from "../provider/Services/ProviderAdapter.ts"; import { makeMoveQueue, type MoveQueueShape } from "./MoveQueue.ts"; import type { ThreadMoveBatchRow } from "./ThreadMoveBatchRepository.ts"; -import type { QueuedMoveStart } from "./ThreadMoves.ts"; +import type { QueuedMoveStart, ThreadMovesShape } from "./ThreadMoves.ts"; const now = "2026-11-15T10:00:00.000Z"; const PROJECT = ProjectId.make("project-1"); @@ -67,6 +71,11 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) { beforeQuiesce: null as null | (() => Effect.Effect), /** Runs right before a Cancel lands, as if the start won the race. */ beforeUnqueue: null as null | (() => Effect.Effect), + /** What the target takes (docs/design/fleet.md, Part 3e): everything, unless a test says. */ + takes: { threadState: true, generalChats: true } as ThreadMoveTakes, + /** What the target answers before the stop, asked whether it takes what the thread carries. */ + carryAnswer: { kind: "ok" } as Effect.Success>, + carryChecks: 0, }; const dispatch = (command: OrchestrationCommand): Effect.Effect => @@ -146,6 +155,7 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) { target: { environmentId: MAC_MINI, label: "Mac mini" }, agent, queuedRequestId: input.requestId, + targetTakes: state.takes, createdAt: now, }).pipe(Effect.result); return started._tag === "Success" @@ -173,7 +183,18 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) { state.quiesceCalls += 1; return state.confirmation; }), - checkQueue: () => Effect.succeed({ label: "Mac mini" }), + restoreOwedThreadIds: Effect.sync(() => + model.threads + .filter((thread) => (thread.moveRestoreOwed ?? null) !== null) + .map((thread) => thread.id), + ), + setsCheckBacks: () => Effect.succeed(true), + checkQueue: () => Effect.sync(() => ({ label: "Mac mini", takes: state.takes })), + checkCarry: () => + Effect.sync(() => { + state.carryChecks += 1; + return state.carryAnswer; + }), describeTargets: Effect.succeed([]), startQueued, batches: { @@ -320,8 +341,10 @@ describe("MoveQueue", () => { await h.close(); }); - it("ends as blocked when the agent set a check-back during the turn", async () => { + it("ends as blocked when the agent set a check-back during the turn, for a computer that can't take it", async () => { const h = await harness(); + // An older computer: check-backs don't travel to it. + h.state.takes = {}; await h.startReactor(); await h.setSession("running", { activeTurnId: TURN }); await h.queueMove(); @@ -515,6 +538,8 @@ describe("MoveQueue, several threads at once", () => { it("decides each thread on its own and answers for every one of them", async () => { const h = await harness(); + // An older computer: pull request switches don't travel to it. + h.state.takes = {}; await h.startReactor(); await addBlockedThread(h); await h.setSession("running", { activeTurnId: TURN }); @@ -592,3 +617,257 @@ describe("MoveQueue, several threads at once", () => { await h.close(); }); }); + +describe("MoveQueue, what a thread had going (Part 3e)", () => { + const GOAL = { + threadId: THREAD, + objective: "Make the suite pass", + status: "active" as const, + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: now, + updatedAt: now, + }; + /** The seeded thread with `patch` applied: what it has going when the test starts. */ + const seededWith = async (patch: Partial) => { + const model = await seeded(); + return { + ...model, + threads: model.threads.map((thread) => + thread.id === THREAD ? ({ ...thread, ...patch } as OrchestrationThread) : thread, + ), + }; + }; + const queuedMessage = (id: string) => + ({ + messageId: MessageId.make(id), + text: "and then this", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }) as OrchestrationQueuedFollowUp; + + it("a target that doesn't take what the thread carries ends the move before anything is stopped", async () => { + const h = await harness({ model: await seededWith({ goal: GOAL }) }); + h.state.carryAnswer = { + kind: "blocked", + words: "Update Threadlines on Mac mini to move this thread: it has a goal.", + }; + await h.startReactor(); + await h.setSession("ready"); + await h.queueMove(); + await waitFor(() => (h.thread().pendingMove ?? null) === null, "the wait to end"); + expect(h.state.quiesceCalls).toBe(0); + expect(h.thread().session?.status).toBe("ready"); + expect(h.thread().lastMoveOutcome).toMatchObject({ + result: "not_moved", + reason: "blocked", + words: "Update Threadlines on Mac mini to move this thread: it has a goal.", + }); + // Nothing was stopped, so nothing is owed back. + expect(h.thread().moveRestoreOwed ?? null).toBeNull(); + await h.close(); + }); + + it("a target that can't be reached holds the move with its agent still at work", async () => { + const h = await harness({ model: await seededWith({ goal: GOAL }) }); + h.state.carryAnswer = { kind: "unreachable", words: "Waiting for Mac mini to connect." }; + await h.startReactor(); + await h.setSession("ready"); + await h.queueMove(); + await waitFor( + () => h.thread().pendingMove?.hold?.kind === "target_unreachable", + "the move to be held", + ); + expect(h.state.quiesceCalls).toBe(0); + expect(h.thread().pendingMove?.stage).toBe("waiting"); + h.state.carryAnswer = { kind: "ok" }; + await h.linkChanged(); + await waitFor(() => (h.thread().move ?? null) !== null, "the move to start"); + expect(h.thread().move?.interrupted).toMatchObject({ goalActive: true }); + await h.close(); + }); + + it("a cancel puts back the goal and the check-backs its stop took, the agent told ahead of the queue", async () => { + const h = await harness({ + model: await seededWith({ + goal: GOAL, + checkBacks: [ + { + id: "check-back-1", + participantId: null, + scheduledFor: "2026-11-15T12:00:00.000Z", + exact: true, + recurring: false, + prompt: "Look at CI on #212", + durable: false, + }, + ], + queuedFollowUps: [queuedMessage("q-1")], + }), + }); + h.state.online = false; + await h.startReactor(); + await h.setSession("ready"); + const { requestId } = await h.queueMove("stop-now"); + await waitFor( + () => h.thread().pendingMove?.hold?.kind === "target_unreachable", + "the move to be held", + ); + // The stop ended the check-back, as Claude's runtime reports it. + await h.dispatch({ + type: "thread.check-backs.set", + commandId: nextCommandId(), + threadId: THREAD, + participantId: null, + checkBacks: [], + createdAt: now, + }); + await h.run(h.queue.unqueue({ threadId: THREAD, requestId })); + await waitFor( + () => h.thread().queuedFollowUps?.[0]?.afterMove === true, + "the agent to be told", + ); + const [told, mine] = h.thread().queuedFollowUps ?? []; + expect(told?.text).toContain("The move to Mac mini didn't happen"); + expect(told?.text).toContain("Your goal is still on: Make the suite pass. Carry on with it."); + expect(told?.text).toContain("Look at CI on #212"); + expect(mine?.messageId).toBe("q-1"); + // Only the goal's hand-over to the provider is left (the reactor's, after the message). + expect(h.thread().moveRestoreOwed).toMatchObject({ goalOwed: true }); + await h.close(); + }); + + it("a cancel sends the queue that waited for the move", async () => { + const h = await harness({ + model: await seededWith({ queuedFollowUps: [queuedMessage("q-1")] }), + }); + h.state.online = false; + await h.startReactor(); + await h.setSession("ready"); + const { requestId } = await h.queueMove(); + await waitFor( + () => h.thread().pendingMove?.hold?.kind === "target_unreachable", + "the move to be held", + ); + await h.run(h.queue.unqueue({ threadId: THREAD, requestId })); + await waitFor(() => (h.thread().queuedFollowUps ?? []).length === 0, "the queue to be sent"); + // Sent as its turn: the message is the thread's now. + expect(h.thread().messages.map((message) => message.id)).toContain("q-1"); + expect(h.thread().moveRestoreOwed ?? null).toBeNull(); + await h.close(); + }); + + it("a dropped move puts back what its stop took", async () => { + const h = await harness({ model: await seededWith({ goal: GOAL }) }); + await h.startReactor(); + await h.setSession("ready"); + await h.queueMove("stop-now"); + await waitFor(() => (h.thread().move ?? null) !== null, "the move to start"); + const transferId = h.thread().move!.transferId; + await h.dispatch({ + type: "thread.move.abort", + commandId: nextCommandId(), + threadId: THREAD, + transferId, + reason: "Mac mini didn't allow the move.", + code: "denied", + createdAt: now, + }); + await waitFor( + () => h.thread().queuedFollowUps?.[0]?.afterMove === true, + "the agent to be told", + ); + expect(h.thread().queuedFollowUps?.[0]?.text).toContain("Your goal is still on"); + await h.close(); + }); + + it("what a move owes back is still paid after a restart", async () => { + const first = await harness({ model: await seededWith({ goal: GOAL }) }); + first.state.online = false; + await first.setSession("ready"); + const { requestId } = await first.queueMove("stop-now"); + // The last process recorded the cancel, and stopped before it paid. + await first.dispatch({ + type: "thread.move.unqueue", + commandId: nextCommandId(), + threadId: THREAD, + requestId, + createdAt: now, + }); + expect(first.thread().moveRestoreOwed?.interrupted).toMatchObject({ goalActive: true }); + await first.close(); + + const restarted = await harness({ model: first.model() }); + await restarted.startReactor(); + await waitFor( + () => restarted.thread().queuedFollowUps?.[0]?.afterMove === true, + "the agent to be told", + ); + expect(restarted.thread().moveRestoreOwed).toMatchObject({ goalOwed: true }); + await restarted.close(); + }); +}); + +describe("MoveQueue, a put-back a restart cut short (Part 3e)", () => { + const at = "2026-11-15T09:00:00.000Z"; + const target = { environmentId: MAC_MINI, label: "Mac mini" }; + const withRecord = async (patch: Partial) => { + const model = await seeded(); + return { + ...model, + threads: model.threads.map((thread) => + thread.id === THREAD ? ({ ...thread, ...patch } as OrchestrationThread) : thread, + ), + }; + }; + + it("sends the message it wrote, still queued when the last process stopped", async () => { + const told = MessageId.make("m-told"); + const h = await harness({ + model: await withRecord({ + moveRestoreOwed: { target, told, goalOwed: true, at }, + queuedFollowUps: [ + { + messageId: told, + text: "The move to Mac mini didn't happen.", + attachments: [], + afterMove: true, + runtimeMode: "auto", + interactionMode: "default", + createdAt: at, + }, + ], + }), + }); + await h.startReactor(); + await waitFor(() => h.thread().messages.some((message) => message.id === told), "sent"); + expect(h.thread().messages.find((message) => message.id === told)?.afterMove).toBe(true); + // The goal still waits for that turn to end (the reactor's to give). + expect(h.thread().moveRestoreOwed).toMatchObject({ goalOwed: true }); + await h.close(); + }); + + it("gives the goal back once everything else went, and the record clears", async () => { + const h = await harness({ + model: await withRecord({ + moveRestoreOwed: { target, goalOwed: true, at }, + goal: { + threadId: THREAD, + objective: "Make the suite pass", + status: "paused", + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: at, + updatedAt: at, + }, + }), + }); + await h.startReactor(); + await waitFor(() => (h.thread().moveRestoreOwed ?? null) === null, "the record to clear"); + await h.close(); + }); +}); diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts index b158f9306..a6f15d54d 100644 --- a/apps/server/src/moves/MoveQueue.ts +++ b/apps/server/src/moves/MoveQueue.ts @@ -21,6 +21,7 @@ import { randomUUID } from "node:crypto"; import { CommandId, + MessageId, type OrchestrationCommand, type OrchestrationEvent, type OrchestrationThread, @@ -54,11 +55,14 @@ import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; import { ComputerLinks } from "../links/ComputerLinks.ts"; +import { derivedUuid } from "../orchestration/childRequestIds.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { firstMoveBlock, + isRestorePaid, moveWaitsOf, + restoreMessageText, sameMoveStatus, type ThreadMoveRefusalEntry, threadMoveRefusals, @@ -124,8 +128,13 @@ export interface MoveQueueDeps { readonly readContext: (threadId: ThreadId) => Effect.Effect; /** Threads with a queued move, for the startup scan. */ readonly pendingThreadIds: Effect.Effect>; + /** Threads a move that didn't happen still owes (moveRestoreOwed), for the startup scan. */ + readonly restoreOwedThreadIds: Effect.Effect>; + /** Whether the thread's agent sets itself check-backs (the put-back message says what to do). */ + readonly setsCheckBacks: (thread: OrchestrationThread) => Effect.Effect; readonly quiesce: (threadId: ThreadId) => Effect.Effect; readonly checkQueue: ThreadMovesShape["checkQueue"]; + readonly checkCarry: ThreadMovesShape["checkCarry"]; /** Every linked computer, described once, for a batch. */ readonly describeTargets: ThreadMovesShape["describeTargets"]; readonly startQueued: ThreadMovesShape["startQueued"]; @@ -231,7 +240,12 @@ const sessionMark = (thread: OrchestrationThread) => { /** A thread's move checks, from the thread alone: no other thread or project. */ const localRefusals = (thread: OrchestrationThread) => - threadMoveRefusals({ projects: [], threads: [thread] }, thread); + threadMoveRefusals( + { projects: [], threads: [thread] }, + thread, + // What the target said it takes, when the move was queued. + thread.pendingMove?.targetTakes, + ); interface TrackedMove { requestId: ThreadMoveRequestId; @@ -446,9 +460,41 @@ export const makeMoveQueue = ( if (yield* settleRefusals(threadId, pending, localRefusals(thread))) return; const context = yield* deps.readContext(threadId); if (context === null) return yield* forget(threadId); - const refusals = threadMoveRefusals(context.view, context.thread); + const refusals = threadMoveRefusals( + context.view, + context.thread, + context.thread.pendingMove?.targetTakes, + ); if (yield* settleRefusals(threadId, pending, refusals)) return; - yield* report(threadId, pending, [], pending.hold ?? null); + // Before anything is stopped: whether the target takes what the thread + // carries (docs/design/fleet.md, Part 3e). One that doesn't ends the + // move here, with nothing to put back; one that can't be reached holds + // it, its agent still at work. + if (pending.stage === "waiting") { + const carried = yield* deps.checkCarry({ + threadId, + targetEnvironmentId: pending.target.environmentId, + label: pending.target.label, + }); + if (carried.kind === "blocked") { + yield* end(threadId, requestId, "blocked", carried.words); + return; + } + if (carried.kind === "unreachable") { + yield* report(threadId, pending, [], { + kind: "target_unreachable", + words: carried.words, + }); + return yield* held(threadId, entry); + } + } + // Waiting, only that answer held it; it is in now. + yield* report( + threadId, + pending, + [], + pending.stage === "waiting" ? null : (pending.hold ?? null), + ); // The barrier: the fence goes up and its sessions stop. if (pending.stage === "waiting" || !sessionStopped(thread)) { @@ -525,6 +571,138 @@ export const makeMoveQueue = ( } }); + // ------------------------------------------------------------------------- + // Put back (docs/design/fleet.md, Part 3e): what a move that didn't happen + // owes the thread, from the record its end left (moveRestoreOwed). + // ------------------------------------------------------------------------- + + /** Threads being paid now, so two events for one thread pay once. */ + const paying = new Set(); + + /** + * Pays what the thread is owed, in one decision that clears the record: + * the goal that was working is on again and its agent is told (with its + * check-backs to set again), and the queue that waited is sent. A thread + * that queued another move since carries it there instead. Fails, and is + * tried again, while the record stays. + */ + const payRestore = ( + threadId: ThreadId, + options: { readonly attempt?: number; readonly startup?: boolean } = {}, + ): Effect.Effect => + Effect.gen(function* () { + const attempt = options.attempt ?? 0; + if (paying.has(threadId)) return; + paying.add(threadId); + yield* Effect.gen(function* () { + const thread = yield* deps.readThread(threadId); + const owed = thread?.moveRestoreOwed ?? null; + if (thread === null || owed === null) return; + if ((thread.pendingMove ?? null) !== null || (thread.move ?? null) !== null) return; + const now = yield* nowIso; + // Paid, with its last steps left: the reactor takes them as turns + // end. Only a restart in between needs this: the message it wrote + // (or the queue after it) is sent, or once all of it went, the + // goal is given back and the record clears. + if (isRestorePaid(owed)) { + if (options.startup !== true) return; + const busy = + thread.session?.status === "running" || thread.session?.status === "starting"; + if (busy) return; + const head = (thread.queuedFollowUps ?? [])[0]; + if (head !== undefined) { + yield* deps.dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make( + `server:thread-move-restore:${threadId}:${owed.at}:${head.messageId}`, + ), + threadId, + messageId: head.messageId, + createdAt: now, + }); + return; + } + const goal = thread.goal; + if ( + owed.goalOwed === true && + (goal?.status === "active" || goal?.status === "paused") + ) { + // A resume: the provider is given the goal the thread reads. + yield* deps.dispatch({ + type: "thread.goal.set", + commandId: CommandId.make(`server:thread-move-restore:${threadId}:${owed.at}:goal`), + threadId, + status: "active", + createdAt: now, + }); + } + yield* deps.dispatch({ + type: "thread.move.restore", + commandId: CommandId.make( + `server:thread-move-restore:${threadId}:${owed.at}:finished`, + ), + threadId, + at: owed.at, + finished: true, + createdAt: now, + }); + return; + } + const text = restoreMessageText(thread, owed, now, yield* deps.setsCheckBacks(thread)); + const busy = + thread.session?.status === "running" || thread.session?.status === "starting"; + // Told something, the message goes first and the queue follows it; + // nothing to tell, an idle thread sends its queue now. A turn at + // work sends it as it ends, as always. + const head = (thread.queuedFollowUps ?? [])[0]; + // A send that was refused once isn't tried again: the queue is left + // for the user, and what was owed is still paid. + const sendQueued = + attempt === 0 && text === null && owed.queued === true && !busy && head !== undefined + ? head.messageId + : undefined; + yield* deps.dispatch({ + type: "thread.move.restore", + commandId: CommandId.make(`server:thread-move-restore:${threadId}:${owed.at}`), + threadId, + at: owed.at, + ...(text !== null + ? { + message: { + messageId: MessageId.make(derivedUuid("move-restore", threadId, owed.at)), + text, + }, + } + : {}), + ...(sendQueued !== undefined ? { sendQueued } : {}), + createdAt: now, + }); + }).pipe( + Effect.catch((error) => + Effect.logWarning("move queue: what a move owed couldn't be put back yet", { + threadId, + detail: error.message, + }).pipe( + // A restart tries again after the last of these. + Effect.andThen( + attempt >= 3 + ? Effect.void + : Effect.sleep(retryDelay(attempt)).pipe( + Effect.andThen( + Effect.suspend(() => + payRestore(threadId, { ...options, attempt: attempt + 1 }), + ), + ), + Effect.forkIn(scope), + Effect.asVoid, + ), + ), + ), + ), + Effect.ensuring(Effect.sync(() => paying.delete(threadId))), + ); + }); + // ------------------------------------------------------------------------- // The service. // ------------------------------------------------------------------------- @@ -540,7 +718,7 @@ export const makeMoveQueue = ( }, ) => Effect.gen(function* () { - const { label } = yield* deps.checkQueue({ + const { label, takes } = yield* deps.checkQueue({ threadId: input.threadId, targetEnvironmentId: input.targetEnvironmentId, agent: input.agent, @@ -558,6 +736,7 @@ export const makeMoveQueue = ( mode: input.mode, requestedBy: input.requestedBy ?? { kind: "user" }, ...(batch !== undefined ? { batchId: batch.batchId } : {}), + targetTakes: takes, createdAt: yield* nowIso, }) .pipe(Effect.mapError((error) => moveError(error.message))); @@ -741,6 +920,10 @@ export const makeMoveQueue = ( yield* schedule(threadId, Duration.zero); } } + // What moves that didn't happen still owe (a restart before it was paid). + for (const threadId of yield* deps.restoreOwedThreadIds) { + yield* payRestore(threadId, { startup: true }); + } }).pipe( Effect.catchCause((cause) => Effect.logWarning("move queue: the queued moves couldn't be read", { cause }), @@ -770,6 +953,16 @@ export const makeMoveQueue = ( } return; } + // A move that didn't happen owes the thread what it took. + if ( + event.type === "thread.move-restore-set" && + event.payload.moveRestoreOwed !== null + ) { + return yield* payRestore(event.payload.threadId).pipe( + Effect.forkIn(scope), + Effect.asVoid, + ); + } // Another thread working in the same folder holds a move: any // session change anywhere is a reason to look again. if (event.type === "thread.session-set") { @@ -837,8 +1030,22 @@ export const MoveQueueLive = Layer.effect( Effect.map((rows) => rows.map((row) => row.threadId)), Effect.orDie, ), + restoreOwedThreadIds: sql<{ readonly threadId: ThreadId }>` + SELECT thread_id AS "threadId" + FROM projection_threads + WHERE move_restore_owed_json IS NOT NULL AND deleted_at IS NULL + `.pipe( + Effect.map((rows) => rows.map((row) => row.threadId)), + Effect.orDie, + ), + setsCheckBacks: (thread) => + providers.getCapabilities(thread.modelSelection.instanceId).pipe( + Effect.map((capabilities) => capabilities.checkBacks === "supported"), + Effect.orElseSucceed(() => false), + ), quiesce: providers.quiesceThread, checkQueue: threadMoves.checkQueue, + checkCarry: threadMoves.checkCarry, describeTargets: threadMoves.describeTargets, startQueued: threadMoves.startQueued, cancelMove: threadMoves.cancel, diff --git a/apps/server/src/moves/ThreadActionGate.ts b/apps/server/src/moves/ThreadActionGate.ts new file mode 100644 index 000000000..29aac1b9b --- /dev/null +++ b/apps/server/src/moves/ThreadActionGate.ts @@ -0,0 +1,38 @@ +/** + * One gate per thread, in this process, between what acts for a thread on + * its own and the move that freezes it (docs/design/fleet.md, Part 3e, + * "Review changes" 1). The pull request watcher holds it from the read that + * decides to act through the act itself (a merge, a turn, a re-queue), and + * reads the thread's move state again under it. A move takes it around the + * freeze, so an act already under way finishes first, and every act after + * reads the thread as moving and stands down. + * + * Only threads that act or move contend, one key each, so the watcher's + * sweep over other threads never waits. After a restart the freeze is in + * the projection, which the watcher reads first anyway. + */ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { makeKeyedLock } from "../links/keyedLock.ts"; + +export interface ThreadActionGateShape { + /** Runs `effect` holding the thread's gate: no freeze of it can land meanwhile. */ + readonly withThread: ( + threadId: string, + effect: Effect.Effect, + ) => Effect.Effect; +} + +export class ThreadActionGate extends Context.Service()( + "threadlines/moves/ThreadActionGate", +) {} + +/** A gate of its own, for one server (or one test). */ +export const makeThreadActionGate = (): ThreadActionGateShape => { + const lock = makeKeyedLock(); + return { withThread: (threadId, effect) => lock(threadId)(effect) }; +}; + +export const ThreadActionGateLive = Layer.sync(ThreadActionGate, makeThreadActionGate); diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index 4ff935cd6..29f3f13b0 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -1,13 +1,16 @@ import { EnvironmentId, + MessageId, type ModelSelection, type OrchestrationThread, + type OrchestrationThreadGoal, type PeerDescriptor, type PeerMoveState, ProviderDriverKind, ProviderInstanceId, ThreadId, type ThreadMovePreview, + TurnId, } from "@threadlines/contracts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -21,7 +24,8 @@ import { previewManyThread, targetPreviewOf, } from "./ThreadMoves.ts"; -import { MOVE_MAX_BYTES, nativeSessionFits } from "./moveExport.ts"; +import { MOVE_MAX_BYTES, moveThreadStateOf, nativeSessionFits } from "./moveExport.ts"; +import { carryBringsWords, threadMoveCarry } from "../orchestration/threadMoveCarry.ts"; import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts"; const THREAD = ThreadId.make("thread-1"); @@ -249,3 +253,201 @@ describe("offerUntilTaken", () => { expect(seen).toEqual({ offers: 1, waiting: 0 }); }); }); + +describe("what a thread carries, as the dialog says it (Part 3e)", () => { + const goal = (status: OrchestrationThreadGoal["status"], tokenBudget: number | null = null) => ({ + threadId: THREAD, + objective: "Make the suite pass", + status, + tokenBudget, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: "2026-11-17T10:00:00.000Z", + updatedAt: "2026-11-17T10:00:00.000Z", + }); + const plan = (index: number, waiting = false) => ({ + id: `plan-${index}`, + turnId: waiting ? TurnId.make("turn-last") : TurnId.make(`turn-${index}`), + planMarkdown: `${index}. Do it`, + implementedAt: waiting ? null : "2026-11-17T10:00:00.000Z", + implementationThreadId: null, + dismissedAt: null, + createdAt: "2026-11-17T10:00:00.000Z", + updatedAt: "2026-11-17T10:00:00.000Z", + }); + const threadWith = (patch: Partial) => + ({ + id: THREAD, + projectId: "project-1", + modelSelection: codex, + goal: null, + checkBacks: [], + queuedFollowUps: [], + proposedPlans: [], + latestTurn: null, + pullRequestAutoFix: false, + pullRequestAutoMerge: null, + linkedPullRequests: [], + ...patch, + }) as unknown as OrchestrationThread; + const view = { projects: [{ id: "project-1", kind: "project" }] } as never; + const peer = (extra: Partial) => + ({ + environmentId: MAC_MINI, + label: "Mac mini", + access: "allowed", + agents: [ + { ...agents[0]!, threadGoals: true, goalBudget: false, checkBacks: true }, + { ...agents[1]!, threadGoals: true, goalBudget: true, checkBacks: false }, + ], + defaultAgent: claude, + projects: [{ canonicalKey: "example.com/repo", name: "Threadlines" }], + moves: true, + ...extra, + }) as unknown as PeerDescriptor; + const target = (described: PeerDescriptor) => ({ + environmentId: MAC_MINI, + label: "Mac mini", + described: Option.some(described), + }); + const place = { canonicalKey: "example.com/repo", subdirectory: "", rootPath: "/repo" }; + + it("a computer that can't take what the thread has going is refused, in words that say why", () => { + const thread = threadWith({ goal: goal("active") }); + const carry = threadMoveCarry(view, thread); + const older = targetPreviewOf(target(peer({})), { thread, place, carry }); + expect(older.refusal).toBe( + "Update Threadlines on Mac mini to move this thread: it has a goal.", + ); + // Never as the code an older app reads as "set the project up there". + expect(older.refusalCode).toBeUndefined(); + const current = targetPreviewOf(target(peer({ moveThreadState: true })), { + thread, + place, + carry, + }); + expect(current.refusal).toBeUndefined(); + }); + + it("warns per agent picked, in the server's words", () => { + const thread = threadWith({ + goal: goal("active", 50_000), + checkBacks: [ + { + id: "cb-1", + participantId: null, + scheduledFor: "2026-11-17T14:32:00.000Z", + exact: true, + recurring: false, + durable: false, + }, + ], + pullRequestAutoFix: true, + }); + const preview = targetPreviewOf(target(peer({ moveThreadState: true })), { + thread, + place, + carry: threadMoveCarry(view, thread), + gitHubReady: new Map([[MAC_MINI, false]]), + goalHoldsTurn: true, + }); + expect(preview.notes).toEqual([ + { words: "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in." }, + { + words: + "Its goal arrives paused: Claude on Mac mini can't keep its token budget. Resume runs it without one.", + instanceIds: ["mac-claude"], + }, + { + words: "Codex on Mac mini can't set check-backs. It's told once what was planned.", + instanceIds: ["mac-codex"], + }, + { words: "It's working toward its goal. Move when it's done waits until it gets there." }, + ]); + }); + + it("says what comes along, one line each", () => { + const thread = threadWith({ + goal: goal("paused"), + queuedFollowUps: [ + { + messageId: MessageId.make("q-1"), + text: "then this", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: "2026-11-17T10:00:00.000Z", + }, + ], + linkedPullRequests: [ + { number: 212, url: "https://example.com/pull/212", autoFix: true, autoMerge: null }, + ], + }); + expect(carryBringsWords(threadMoveCarry(view, thread))).toEqual([ + "Its goal arrives paused.", + "Auto-fix keeps watching pull request #212 from there.", + "1 queued message is sent there.", + ]); + }); + + it("past 100 plans the oldest stay, the newest (with Implement) always comes, and it says so", () => { + const plans = [...Array.from({ length: 102 }, (_, index) => plan(index)), plan(102, true)]; + const thread = threadWith({ + proposedPlans: plans, + latestTurn: { turnId: TurnId.make("turn-last") } as OrchestrationThread["latestTurn"], + }); + const carry = threadMoveCarry(view, thread); + expect(carry.proposedPlans).toHaveLength(100); + expect(carry.proposedPlans.at(-1)?.id).toBe("plan-102"); + expect(carry.plansLeftBehind).toBe(3); + expect(carryBringsWords(carry)).toEqual([ + "The plan waits for you there.", + "3 older plans stay on this computer.", + ]); + expect(moveThreadStateOf(carry)).toMatchObject({ plansLeftBehind: 3 }); + }); + + it("a goal that finished is never picked up, whatever the move's stop recorded", () => { + const thread = threadWith({ + goal: goal("complete"), + move: { interrupted: { goalActive: true } } as OrchestrationThread["move"], + }); + expect(moveThreadStateOf(threadMoveCarry(view, thread))?.goal).toMatchObject({ + status: "complete", + pickUp: false, + }); + const working = threadWith({ + goal: goal("paused"), + move: { interrupted: { goalActive: true } } as OrchestrationThread["move"], + }); + expect(moveThreadStateOf(threadMoveCarry(view, working))?.goal?.pickUp).toBe(true); + }); + it("a batch row keeps the warnings that hold for the agent it moves with", () => { + const thread = threadWith({ + modelSelection: claude, + goal: goal("active", 50_000), + pullRequestAutoFix: true, + }); + const own = targetPreviewOf(target(peer({ moveThreadState: true })), { + thread, + place, + carry: threadMoveCarry(view, thread), + gitHubReady: new Map([[MAC_MINI, false]]), + }); + // A batch moves it with the agent Mac mini suggests: its own Claude. + expect(own.suggestedAgent?.instanceId).toBe("mac-claude"); + const row = previewManyThread(THREAD, { targets: [own] }, [own]); + expect(row.targetLines).toEqual([ + { + environmentId: MAC_MINI, + notes: [ + { words: "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in." }, + { + words: + "Its goal arrives paused: Claude on Mac mini can't keep its token budget. Resume runs it without one.", + }, + ], + }, + ]); + }); +}); diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts index 5048ceecd..026d4261c 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -39,7 +39,9 @@ import { type ThreadMovePreviewMany, type ThreadMovePreviewManyThread, type ThreadMoveSessionOutcome, + type ThreadMoveNote, type ThreadMoveStartInput, + type ThreadMoveTakes, type ThreadMoveTargetPreview, } from "@threadlines/contracts"; import * as Context from "effect/Context"; @@ -60,12 +62,21 @@ import { ServerConfig } from "../config.ts"; import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"; import { ComputerLinkClient, type PeerClient } from "../links/ComputerLinkClient.ts"; import { ComputerLinkRepository, isUsableLink } from "../links/ComputerLinkRepository.ts"; +import { generalChatThreadScratchCwd } from "../orchestration/generalChats.ts"; +import { + ALL_MOVE_TAKES, + carryBringsWords, + carryNotTaken, + type ThreadMoveCarry, + threadMoveCarry, +} from "../orchestration/threadMoveCarry.ts"; import { firstMoveBlock, moveWaitsOf, threadMoveRefusal, threadMoveRefusals, } from "../orchestration/threadMoveDecisions.ts"; +import { ThreadActionGate } from "./ThreadActionGate.ts"; import type { NativeSessionExport } from "../provider/nativeSession.ts"; import { ProviderService } from "../provider/Services/ProviderService.ts"; import { makeThreadMoveContextReader } from "./threadMoveView.ts"; @@ -79,13 +90,16 @@ import { estimateMoveOtherBytes, inspectMoveCheckout, type MoveCheckout, + moveThreadStateOf, nativeSessionFits, movePayloadPath, readMoveExport, sha256OfFile, summarizeMoveChanges, + summarizeScratchFolder, ThreadMoveFailure, writeMoveExport, + writeScratchExport, } from "./moveExport.ts"; /** @@ -137,7 +151,30 @@ export interface ThreadMovesShape { readonly agent?: ModelSelection | undefined; /** The computers as already described (a batch); absent: described now. */ readonly targets?: ReadonlyArray | undefined; - }) => Effect.Effect<{ readonly label: string }, ThreadMoveError>; + }) => Effect.Effect< + { + readonly label: string; + /** What it takes (ThreadMoveTakes); everything, when it couldn't be reached now. */ + readonly takes: ThreadMoveTakes; + }, + ThreadMoveError + >; + /** + * Before the move's stop (docs/design/fleet.md, Part 3e, "Put back"): + * whether the target takes what the thread carries. `ok` when it carries + * nothing to ask about; `unreachable` when the target doesn't answer; + * `blocked` (with words) when it answered that it doesn't, so the move + * ends before anything here is stopped. + */ + readonly checkCarry: (input: { + readonly threadId: ThreadId; + readonly targetEnvironmentId: EnvironmentId; + readonly label: string; + }) => Effect.Effect< + | { readonly kind: "ok" } + | { readonly kind: "unreachable"; readonly words: string } + | { readonly kind: "blocked"; readonly words: string } + >; /** Starts the thread's queued move `requestId`, now that the thread is free and quiesced. */ readonly startQueued: (input: { readonly threadId: ThreadId; @@ -210,6 +247,72 @@ export function sessionOutcomeFor( * would get of its session; without one, only what holds for every thread * (its default agent is the suggestion). */ +/** What a linked computer takes beyond a plain thread, as it says (ThreadMoveTakes). */ +export function takesOf(peer: PeerDescriptor): ThreadMoveTakes { + return { + ...(peer.moveThreadState === true ? { threadState: true as const } : {}), + ...(peer.moveGeneralChats === true ? { generalChats: true as const } : {}), + }; +} + +/** The name General Chats has on every computer, as the dialog's project line says it. */ +const GENERAL_CHATS_NAME = "General chats"; + +/** + * What won't work on `peer` as it did here, for a thread carrying `carry` + * (docs/design/fleet.md, Part 3e, "What the user sees"), in the server's + * words; a note about some of its agents names them (`instanceIds`). + */ +export function targetNotesOf( + peer: PeerDescriptor, + carry: ThreadMoveCarry, + extra: { + /** Whether GitHub is signed in there for the project; absent: not asked, or it couldn't tell. */ + readonly gitHubReady?: boolean | undefined; + /** The thread's agent here keeps its turn running until its goal is met (Claude). */ + readonly goalHoldsTurn?: boolean | undefined; + }, +): ReadonlyArray { + const notes: ThreadMoveNote[] = []; + const goal = carry.goal; + if (carry.pullRequests !== null && extra.gitHubReady === false) { + notes.push({ + words: `GitHub isn't signed in on ${peer.label}. Auto-fix waits there until you sign in.`, + }); + } + for (const agent of peer.agents) { + if (carry.checkBacks.length > 0 && agent.checkBacks === false) { + notes.push({ + words: `${agent.name} on ${peer.label} can't set check-backs. It's told once what was planned.`, + instanceIds: [agent.instanceId], + }); + } + if (goal !== null && goal.status !== "complete" && agent.threadGoals === false) { + notes.push({ + words: `${agent.name} on ${peer.label} can't keep goals, so its goal stays behind.`, + instanceIds: [agent.instanceId], + }); + } else if ( + goal !== null && + goal.tokenBudget !== null && + ["active", "paused", "usageLimited"].includes(goal.status) && + agent.threadGoals === true && + agent.goalBudget === false + ) { + notes.push({ + words: `Its goal arrives paused: ${agent.name} on ${peer.label} can't keep its token budget. Resume runs it without one.`, + instanceIds: [agent.instanceId], + }); + } + } + if (extra.goalHoldsTurn === true && goal?.status === "active") { + notes.push({ + words: "It's working toward its goal. Move when it's done waits until it gets there.", + }); + } + return notes; +} + export function targetPreviewOf( target: DescribedTarget, forThread: { @@ -219,6 +322,11 @@ export function targetPreviewOf( readonly session?: NativeSessionExport | null | undefined; /** What the move carries besides the session (estimateMoveOtherBytes). */ readonly otherBytes?: number | undefined; + /** What else it carries (threadMoveCarry); absent: not looked at. */ + readonly carry?: ThreadMoveCarry | undefined; + /** Whether GitHub is signed in there, per computer (`peer.move.readiness`). */ + readonly gitHubReady?: ReadonlyMap | undefined; + readonly goalHoldsTurn?: boolean | undefined; } | null, ): ThreadMoveTargetPreview { const { environmentId, label } = target; @@ -233,25 +341,40 @@ export function targetPreviewOf( } const peer = target.described.value; const place = forThread?.place ?? null; + const carry = forThread?.carry; + // A general chat lands in General chats there: no project to match. + const generalChat = carry?.generalChat === true; const project = - place === null + place === null || generalChat ? undefined : peer.projects.find( (entry) => entry.canonicalKey === place.canonicalKey && (entry.subdirectory === undefined || entry.subdirectory === place.subdirectory), ); - const noProject = forThread !== null && project === undefined; + const noProject = forThread !== null && !generalChat && project === undefined; + // What the thread has going that this computer doesn't take (Part 3e): it + // needs a newer Threadlines, whatever else it has. + const notTaken = carry === undefined ? null : carryNotTaken(carry, takesOf(peer)); const refusal = peer.moves !== true ? `${peer.label} needs a newer Threadlines to take moved threads.` : peer.access === "off" ? `${peer.label} doesn't take work from this computer.` - : noProject - ? `${peer.label} doesn't have this project.` - : peer.agents.length === 0 - ? `${peer.label} has no agent ready.` - : undefined; + : notTaken !== null + ? `Update Threadlines on ${peer.label} to move this thread: ${notTaken}.` + : noProject + ? `${peer.label} doesn't have this project.` + : peer.agents.length === 0 + ? `${peer.label} has no agent ready.` + : undefined; + const notes = + carry === undefined || refusal !== undefined + ? [] + : targetNotesOf(peer, carry, { + gitHubReady: forThread?.gitHubReady?.get(environmentId), + goalHoldsTurn: forThread?.goalHoldsTurn, + }); const suggested = forThread !== null ? suggestAgent(peer, forThread.thread) @@ -268,10 +391,19 @@ export function targetPreviewOf( environmentId, label: peer.label, ...(refusal !== undefined ? { refusal } : {}), - ...(refusal !== undefined && peer.moves === true && peer.access !== "off" && noProject + ...(refusal !== undefined && + peer.moves === true && + peer.access !== "off" && + notTaken === null && + noProject ? { refusalCode: "no_project" as const } : {}), - ...(project !== undefined ? { projectName: project.name } : {}), + ...(project !== undefined + ? { projectName: project.name } + : generalChat + ? { projectName: GENERAL_CHATS_NAME } + : {}), + ...(notes.length > 0 ? { notes } : {}), access: peer.access, agents: peer.agents, ...(suggested !== undefined ? { suggestedAgent: suggested } : {}), @@ -303,6 +435,10 @@ export function previewManyThread( }, ]; }); + // A general chat's row says where it lands; any thread's, what won't work there. + const targetLines = shown.targets.flatMap((own) => + batchTargetLines(own, shown.folder !== undefined), + ); // A batch moves each thread with the agent its target suggests for it. const sessionOutcomes = shown.targets.flatMap((own) => { const agent = own.suggestedAgent; @@ -321,10 +457,39 @@ export function previewManyThread( ? { waitsFor: shown.waitsFor } : {}), ...(targetRefusals.length > 0 ? { targetRefusals } : {}), + ...(shown.brings !== undefined && shown.brings.length > 0 ? { brings: shown.brings } : {}), + ...(shown.folder !== undefined ? { folder: shown.folder } : {}), + ...(targetLines.length > 0 ? { targetLines } : {}), ...(sessionOutcomes.length > 0 ? { sessionOutcomes } : {}), }; } +/** + * Per computer that takes the thread, its own lines in a batch: the project + * it lands in, and the notes that hold for the agent that computer suggests + * (a batch moves each thread with that one), without naming agents. + */ +function batchTargetLines(own: ThreadMoveTargetPreview, withLanding: boolean) { + if (own.refusal !== undefined) return []; + const projectName = withLanding ? own.projectName : undefined; + const agent = own.suggestedAgent?.instanceId; + const notes = (own.notes ?? []).flatMap((note) => + note.instanceIds === undefined + ? [note] + : agent !== undefined && note.instanceIds.includes(agent) + ? [{ words: note.words }] + : [], + ); + if (projectName === undefined && notes.length === 0) return []; + return [ + { + environmentId: own.environmentId, + ...(projectName !== undefined ? { projectName } : {}), + ...(notes.length > 0 ? { notes } : {}), + }, + ]; +} + /** How long a move waits for a busy computer before offering again: 15 s, 30 s, 1 min, then every 2 min. */ export const busyRetryDelay = (attempt: number) => Duration.seconds(Math.min(15 * 2 ** Math.max(0, attempt), 120)); @@ -424,6 +589,7 @@ const make = Effect.gen(function* () { const config = yield* ServerConfig; const environment = yield* ServerEnvironment; const providers = yield* ProviderService; + const actionGate = yield* ThreadActionGate; const descriptor = yield* environment.getDescriptor; const moveDir = (transferId: string) => NodePath.join(config.stateDir, "moves", transferId); @@ -498,7 +664,10 @@ const make = Effect.gen(function* () { if (context === null) return yield* moveError("That thread doesn't exist."); const { thread, view } = context; const project = view.projects.find((entry) => entry.id === thread.projectId); - const refusals = threadMoveRefusals(view, thread); + // As if the other computer took everything (docs/design/fleet.md, Part + // 3e): one that doesn't says so as its own refusal. + const refusals = threadMoveRefusals(view, thread, ALL_MOVE_TAKES); + const carry = threadMoveCarry(view, thread); const pending = thread.pendingMove ?? null; let refusal: string | null = firstMoveBlock(refusals)?.words ?? @@ -506,9 +675,17 @@ const make = Effect.gen(function* () { ? `A move to ${pending.target.label} is already waiting. Cancel it first.` : null); let changes: ThreadMovePreview["changes"]; + let folder: ThreadMovePreview["folder"]; let place: ProjectPlace | null = null; let checkout: MoveCheckout | null = null; - if (project !== undefined && project.kind !== "general-chat") { + if (project !== undefined && project.kind === "general-chat") { + // Its folder goes, every file in it, within the move's limits. + const summary = yield* summarizeScratchFolder( + generalChatThreadScratchCwd(project.workspaceRoot, thread.id, NodePath), + ); + folder = { files: summary.files, bytes: summary.bytes }; + refusal ??= summary.refusal; + } else if (project !== undefined) { const source = yield* whereFrom(thread, project.workspaceRoot).pipe(Effect.result); if (source._tag === "Success") { place = source.success.place; @@ -544,24 +721,88 @@ const make = Effect.gen(function* () { thread, attachmentsDir: config.attachmentsDir, }) - : 0; + : (folder?.bytes ?? 0); + // The dialogs' warnings: GitHub's sign-in there, asked only for a + // thread whose switches are on, and whether its goal holds the turn here. + const gitHubReady = + options.withSession === true && carry.pullRequests !== null && place !== null + ? yield* readinessOf(described, place.canonicalKey) + : undefined; + const goalHoldsTurn = + options.withSession === true && carry.goal?.status === "active" + ? yield* providers.getCapabilities(thread.modelSelection.instanceId).pipe( + Effect.map((capabilities) => capabilities.threadGoalPause === "unsupported"), + Effect.orElseSucceed(() => false), + ) + : false; const targets = described.map((target) => - targetPreviewOf(target, { thread, place, session, otherBytes }), + targetPreviewOf(target, { + thread, + place, + session, + otherBytes, + carry, + gitHubReady, + goalHoldsTurn, + }), ); const waitsFor = moveWaitsOf(refusals); + const brings = carryBringsWords(carry).map((words) => ({ words })); return { thread, + carry, + described, // A move that doesn't wait refuses a busy thread too. - busy: threadMoveRefusal(view, thread), + busy: threadMoveRefusal(view, thread, ALL_MOVE_TAKES), preview: { ...(refusal !== null ? { refusal } : {}), ...(waitsFor.length > 0 ? { waitsFor } : {}), ...(changes !== undefined ? { changes } : {}), + ...(folder !== undefined ? { folder } : {}), + ...(brings.length > 0 ? { brings } : {}), targets, } satisfies ThreadMovePreview, }; }); + /** + * Whether GitHub is signed in for the project on each computer that takes + * thread state (`peer.move.readiness`); one that doesn't answer in time is + * left out (the dialog says nothing then). + */ + const readinessOf = (described: ReadonlyArray, canonicalKey: string) => + Effect.gen(function* () { + const answers = yield* Effect.forEach( + described, + (target) => + Option.isNone(target.described) || target.described.value.moveThreadState !== true + ? Effect.succeed(null) + : client + .withPeer(target.environmentId, (peer) => + peer["peer.move.readiness"]({ canonicalKey }), + ) + .pipe( + Effect.timeout(DESCRIBE_WAIT), + Effect.map((answer) => + answer.gitHubReady === undefined + ? null + : ([target.environmentId, answer.gitHubReady] as const), + ), + Effect.orElseSucceed(() => null), + ), + { concurrency: "unbounded" }, + ); + return new Map(answers.filter((entry) => entry !== null)); + }); + + /** What a computer just described takes; one that couldn't be reached is taken to take everything. */ + const takesFrom = (described: ReadonlyArray, environmentId: EnvironmentId) => { + const target = described.find((entry) => entry.environmentId === environmentId); + return target === undefined || Option.isNone(target.described) + ? ALL_MOVE_TAKES + : takesOf(target.described.value); + }; + const preview: ThreadMovesShape["preview"] = (threadId) => inspect(threadId, { withSession: true }).pipe(Effect.map((inspected) => inspected.preview)); @@ -582,27 +823,38 @@ const make = Effect.gen(function* () { return { threads, targets } satisfies ThreadMovePreviewMany; }); - /** Freezes the thread for its move (`thread.move.start`); the decider checks it again. */ + /** + * Freezes the thread for its move (`thread.move.start`); the decider checks + * it again, against what the other computer just said it takes. Held in the + * thread's action gate, so an act for it already under way here (a merge, + * a turn the pull request watcher starts) finishes first, and every act + * after reads the thread as moving. + */ const dispatchStart = ( threadId: ThreadId, target: ThreadMoveTargetPreview, agent: ModelSelection, + takes: ThreadMoveTakes, queuedRequestId?: ThreadMoveRequestId, ) => - Effect.gen(function* () { - const transferId = ThreadMoveId.make(randomUUID()); - yield* engine.dispatch({ - type: "thread.move.start", - commandId: CommandId.make(`server:thread-move:${transferId}:start`), - threadId, - transferId, - target: { environmentId: target.environmentId, label: target.label }, - agent, - ...(queuedRequestId !== undefined ? { queuedRequestId } : {}), - createdAt: yield* nowIso, - }); - return transferId; - }); + actionGate.withThread( + threadId, + Effect.gen(function* () { + const transferId = ThreadMoveId.make(randomUUID()); + yield* engine.dispatch({ + type: "thread.move.start", + commandId: CommandId.make(`server:thread-move:${transferId}:start`), + threadId, + transferId, + target: { environmentId: target.environmentId, label: target.label }, + agent, + ...(queuedRequestId !== undefined ? { queuedRequestId } : {}), + targetTakes: takes, + createdAt: yield* nowIso, + }); + return transferId; + }), + ); const start: ThreadMovesShape["start"] = (input) => Effect.gen(function* () { @@ -615,22 +867,50 @@ const make = Effect.gen(function* () { if ("unreachable" in checked) { return yield* moveError(checked.unreachable.refusal ?? "That computer can't be reached."); } - const transferId = yield* dispatchStart(input.threadId, checked.ok, input.agent).pipe( - Effect.mapError((error) => moveError(error.message)), - ); + const transferId = yield* dispatchStart( + input.threadId, + checked.ok, + input.agent, + takesFrom(inspected.described, input.targetEnvironmentId), + ).pipe(Effect.mapError((error) => moveError(error.message))); return { transferId }; }); const checkQueue: ThreadMovesShape["checkQueue"] = (input) => Effect.gen(function* () { - const shown = (yield* inspect(input.threadId, { + const inspected = yield* inspect(input.threadId, { targets: input.targets, withChanges: false, - })).preview; + }); + const shown = inspected.preview; if (shown.refusal !== undefined) return yield* moveError(shown.refusal); const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent); if ("refusal" in checked) return yield* moveError(checked.refusal); - return { label: "ok" in checked ? checked.ok.label : checked.unreachable.label }; + return { + label: "ok" in checked ? checked.ok.label : checked.unreachable.label, + takes: takesFrom(inspected.described, input.targetEnvironmentId), + }; + }); + + const checkCarry: ThreadMovesShape["checkCarry"] = (input) => + Effect.gen(function* () { + const context = yield* readMoveContext(input.threadId).pipe(Effect.option); + if (Option.isNone(context) || context.value === null) return { kind: "ok" } as const; + const carry = threadMoveCarry(context.value.view, context.value.thread); + if (!carry.needs.threadState && !carry.needs.generalChats) return { kind: "ok" } as const; + const peer = yield* client + .describe(input.targetEnvironmentId, { fresh: true }) + .pipe(Effect.timeout(DESCRIBE_WAIT), Effect.option); + if (Option.isNone(peer)) { + return { kind: "unreachable", words: `Waiting for ${input.label} to connect.` } as const; + } + const notTaken = carryNotTaken(carry, takesOf(peer.value)); + return notTaken === null + ? ({ kind: "ok" } as const) + : ({ + kind: "blocked", + words: `Update Threadlines on ${peer.value.label} to move this thread: ${notTaken}.`, + } as const); }); const startQueued: ThreadMovesShape["startQueued"] = (input) => @@ -656,6 +936,7 @@ const make = Effect.gen(function* () { input.threadId, checked.ok, checked.agent, + takesFrom(inspected.success.described, input.targetEnvironmentId), input.requestId, ).pipe(Effect.result); return started._tag === "Success" @@ -919,9 +1200,35 @@ const make = Effect.gen(function* () { if (Option.isNone(detail)) { return yield* new ThreadMoveFailure({ reason: "This thread couldn't be read." }); } - const { place, checkout } = yield* whereFrom(detail.value, project.workspaceRoot); const nativeSession = yield* sessionToCarry(thread.id, targetEnvironmentId, agent); + // What it had going, for a computer that takes it (docs/design/fleet.md, + // Part 3e); one that doesn't never gets it, and couldn't have been + // offered a thread that needs it. + const takes = detail.value.move?.targetTakes; + const state = + takes?.threadState === true + ? moveThreadStateOf(threadMoveCarry({ projects: model.projects }, detail.value)) + : undefined; + const source = { + environmentId: descriptor.environmentId, + environmentLabel: environment.currentLabel(), + threadId: thread.id, + }; + if (project.kind === "general-chat") { + return yield* writeScratchExport({ + dir, + folder: generalChatThreadScratchCwd(project.workspaceRoot, thread.id, NodePath), + attachmentsDir: config.attachmentsDir, + thread: detail.value, + source, + agent, + nativeSession, + state, + }); + } + const { place, checkout } = yield* whereFrom(detail.value, project.workspaceRoot); return yield* writeMoveExport({ + state, git, checkout, transferId, @@ -931,11 +1238,7 @@ const make = Effect.gen(function* () { projectTitle: project.title, canonicalKey: place.canonicalKey, subdirectory: place.subdirectory, - source: { - environmentId: descriptor.environmentId, - environmentLabel: environment.currentLabel(), - threadId: thread.id, - }, + source, agent, nativeSession, }); @@ -1270,6 +1573,7 @@ const make = Effect.gen(function* () { describeTargets, start, checkQueue, + checkCarry, startQueued, cancel, startReactor, diff --git a/apps/server/src/moves/arrivalMessage.ts b/apps/server/src/moves/arrivalMessage.ts new file mode 100644 index 000000000..c56a85b2e --- /dev/null +++ b/apps/server/src/moves/arrivalMessage.ts @@ -0,0 +1,76 @@ +/** + * The message Threadlines writes for a thread's agent when the thread moved, + * or when its move didn't happen (docs/design/fleet.md, Part 3e, "The + * arrival message" and "Put back"): what the move's stop took from it (a + * goal that was working, check-backs that ended with its session) and what + * to do about each. It is queued ahead of the user's own messages and sent + * like any of them, so the agent gets its conversation first (a carried + * session, or the summary). Pure: the decider and the import both build it. + */ + +/** A check-back as the message names it. */ +export interface ArrivalCheckBack { + readonly scheduledFor: string; + readonly recurring: boolean; + readonly schedule?: string | undefined; + readonly cron?: string | undefined; + readonly description?: string | undefined; + readonly prompt?: string | undefined; +} + +export interface ArrivalMessageInput { + /** `moved`: the thread arrived here from `from`. `stayed`: its move to `to` didn't happen. */ + readonly kind: "moved" | "stayed"; + readonly from: string; + readonly to: string; + /** A goal that was working, to carry on with; null: none. */ + readonly goal: { readonly objective: string } | null; + /** The check-backs its stop ended. */ + readonly checkBacks: ReadonlyArray; + /** The agent here can set check-backs (Claude); false: it is told once, to act on them. */ + readonly canSetCheckBacks: boolean; + /** When the message is written, to tell a time that passed during the move. */ + readonly now: string; +} + +/** When one check-back fires, as the agent reads it. */ +function whenWords(checkBack: ArrivalCheckBack, nowMs: number): string { + if (checkBack.recurring) { + const schedule = checkBack.schedule ?? "on a schedule"; + return checkBack.cron !== undefined ? `${schedule} (${checkBack.cron})` : schedule; + } + const due = Date.parse(checkBack.scheduledFor); + return Number.isFinite(due) && due < nowMs + ? `was due at ${checkBack.scheduledFor}` + : `at ${checkBack.scheduledFor}`; +} + +/** The message a moved thread's agent gets when its user resumes the goal it arrived with. */ +export const resumedGoalMessageText = (objective: string) => + `This thread moved here from another computer, and its goal is on again: ${objective}. Carry on with it.`; + +/** The message, or null when there is nothing to tell the agent. */ +export function arrivalMessageText(input: ArrivalMessageInput): string | null { + if (input.goal === null && input.checkBacks.length === 0) return null; + const nowMs = Date.parse(input.now); + const lines = [ + input.kind === "moved" + ? `This thread moved from ${input.from} to ${input.to}, and your session was restarted for it.` + : `The move to ${input.to} didn't happen, and your session was restarted for it.`, + ]; + if (input.goal !== null) { + lines.push(`- Your goal is still on: ${input.goal.objective}. Carry on with it.`); + } + if (input.checkBacks.length > 0) { + lines.push( + input.canSetCheckBacks + ? "- Your check-backs ended with the move. Run CronList, then set again the ones you still need:" + : "- Your check-backs ended with the move, and you can't set them here. This is what you had planned:", + ); + for (const checkBack of input.checkBacks) { + const what = checkBack.prompt ?? checkBack.description ?? "(no prompt recorded)"; + lines.push(` - ${whenWords(checkBack, nowMs)}: ${what}`); + } + } + return lines.join("\n"); +} diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts index e6ed13cdf..976e6db58 100644 --- a/apps/server/src/moves/moveExport.ts +++ b/apps/server/src/moves/moveExport.ts @@ -18,8 +18,11 @@ import type { ModelSelection, OrchestrationThread, OrchestrationThreadActivity, + PeerMoveGitManifest, PeerMoveManifest, PeerMovePart, + PeerMoveScratchManifest, + PeerMoveThreadState, ThreadId, ThreadImportMessage, ThreadMoveId, @@ -28,6 +31,7 @@ import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import { resolveAttachmentPath } from "../attachmentStore.ts"; +import type { ThreadMoveCarry } from "../orchestration/threadMoveCarry.ts"; import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts"; import type { GitVcsDriverShape } from "../vcs/GitVcsDriver.ts"; @@ -99,6 +103,8 @@ export interface MoveCheckout { /** The last commit the remote has; null when the head itself is there (nothing unpushed). */ readonly baseSha: string | null; readonly unpushedCommits: number; + /** The branch on the remote that `branch` tracks; null: none, or another remote's. */ + readonly upstreamBranch: string | null; } /** @@ -170,6 +176,10 @@ export function inspectMoveCheckout( remoteName, baseSha: baseSha === headSha ? null : baseSha, unpushedCommits: unpushed, + upstreamBranch: + upstream !== null && upstream.startsWith(`${remoteName}/`) + ? upstream.slice(remoteName.length + 1) + : null, }; }); } @@ -406,6 +416,11 @@ export interface MoveExportInput { * within both caps; past either, the move goes without it and says why. */ readonly nativeSession?: NativeSessionExport | null | undefined; + /** + * What the thread had going (moveThreadStateOf), for a computer that takes + * it; its queued messages' attachments travel as parts. + */ + readonly state?: PeerMoveThreadState | undefined; } /** @@ -454,7 +469,7 @@ export function sha256OfFile(path: string) { */ export function writeMoveExport( input: MoveExportInput, -): Effect.Effect { +): Effect.Effect { const { git, checkout, dir } = input; const root = checkout.root; const attempt = Effect.gen(function* () { @@ -566,15 +581,95 @@ export function writeMoveExport( } } const history = exportThreadHistory(input.thread); - const attachmentIds = new Set(); - for (const message of history.messages) { + parts.push(...(yield* attachmentParts(history, input.attachmentsDir, input.state))); + const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); + if (otherBytes > MOVE_MAX_BYTES) { + return yield* fail( + `This thread's changes come to ${Math.ceil(otherBytes / (1024 * 1024))} MB. Moves carry at most 100 MB.`, + ); + } + const session = yield* sessionParts(input.nativeSession ?? null, otherBytes); + parts.push(...session.parts); + + const payload = yield* writePayload(dir, parts); + if (payload === null) return yield* new CheckoutChanged(); + const after = yield* checkoutFingerprint(git, root, afterDiffPath); + yield* fsCall("Couldn't tidy up.", async () => { + await NodeFs.rm(NodePath.join(dir, "bundle.tmp"), { force: true }); + await NodeFs.rm(diffPath, { force: true }); + await NodeFs.rm(afterDiffPath, { force: true }); + }); + if (after.key !== before.key) return yield* new CheckoutChanged(); + + const manifest: PeerMoveGitManifest = { + totalBytes: payload.totalBytes, + sha256: payload.sha256, + parts: payload.table, + source: input.source, + project: { + canonicalKey: input.canonicalKey, + subdirectory: input.subdirectory, + title: input.projectTitle, + }, + git: { + headSha: checkout.headSha, + branch: checkout.branch, + baseSha: checkout.baseSha, + ...(checkout.upstreamBranch !== null ? { upstreamBranch: checkout.upstreamBranch } : {}), + }, + thread: { + title: input.thread.title, + runtimeMode: input.thread.runtimeMode, + interactionMode: input.thread.interactionMode, + messages: history.messages, + activities: history.activities, + ...(input.state !== undefined ? { state: input.state } : {}), + }, + agent: input.agent, + summary: { + messageCount: history.messages.length, + trackedFiles: tracked.length, + untrackedFiles: untracked.length, + unpushedCommits: checkout.unpushedCommits, + }, + ...session.manifest, + }; + yield* writeManifest(dir, manifest); + return manifest; + }); + const changedReason = "The checkout changed while this thread was being packed. Try again."; + return attempt.pipe( + Effect.catchTag("CheckoutChanged", () => attempt), + Effect.catchTag("CheckoutChanged", () => fail(changedReason)), + ); +} + +/** + * The attachments a move carries, one part each: its history's messages', and + * its queued messages' (docs/design/fleet.md, Part 3e, (e)). A missing one + * travels as its name alone. + */ +function attachmentParts( + history: ReturnType, + attachmentsDir: string, + state: PeerMoveThreadState | undefined, +) { + return Effect.gen(function* () { + const parts: PendingPart[] = []; + const seen = new Set(); + const carriers = [...history.messages, ...(state?.queuedFollowUps ?? [])]; + for (const message of carriers) { for (const attachment of message.attachments ?? []) { - if (attachmentIds.has(attachment.id)) continue; - attachmentIds.add(attachment.id); - const path = resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment }); - // A missing attachment travels as its name alone. + if (seen.has(attachment.id)) continue; + seen.add(attachment.id); + const path = resolveAttachmentPath({ attachmentsDir, attachment }); const size = - path === null ? null : yield* fileSize(path).pipe(Effect.orElseSucceed(() => null)); + path === null + ? null + : yield* fsCall("Couldn't read the packed thread.", () => NodeFs.stat(path)).pipe( + Effect.map((stat) => stat.size), + Effect.orElseSucceed(() => null), + ); if (path !== null && size !== null) { parts.push({ kind: "attachment", @@ -585,47 +680,72 @@ export function writeMoveExport( } } } + return parts; + }); +} - const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); - if (otherBytes > MOVE_MAX_BYTES) { - return yield* fail( - `This thread's changes come to ${Math.ceil(otherBytes / (1024 * 1024))} MB. Moves carry at most 100 MB.`, - ); - } - // The agent's session goes last, and only within both caps: past them, - // the move goes without it and the agent gets a summary. - const session = input.nativeSession ?? null; +/** + * The agent's session as parts, last and only within both caps: past them, + * the move goes without it and the agent gets a summary, and the manifest + * says why. A session file that can't be read, or vanished since it was + * found, leaves the session behind; it never fails the move. + */ +function sessionParts(session: NativeSessionExport | null, otherBytes: number) { + return Effect.gen(function* () { const sessionBytes = session?.files.reduce((sum, file) => sum + file.size, 0) ?? 0; const carriesSession = session !== null && nativeSessionFits(sessionBytes, otherBytes); - // Read up front (both caps bound it): a session file that can't be read, - // or vanished since it was found, leaves the session behind and the move - // goes on with a summary, never failing the move itself. - const sessionBytesRead = + const read = session !== null && carriesSession ? yield* Effect.tryPromise(() => Promise.all(session.files.map((file) => NodeFs.readFile(file.absolutePath))), ).pipe(Effect.orElseSucceed(() => null)) : null; - const sessionPacked = + const packed = session !== null && - sessionBytesRead !== null && + read !== null && nativeSessionFits( - sessionBytesRead.reduce((sum, bytes) => sum + bytes.length, 0), + read.reduce((sum, bytes) => sum + bytes.length, 0), otherBytes, ); - if (session !== null && sessionBytesRead !== null && sessionPacked) { - session.files.forEach((file, index) => { - const bytes = sessionBytesRead[index]!; - parts.push({ - kind: "session", - path: file.relPath, - size: bytes.length, - read: () => Promise.resolve(bytes), - }); - }); - } - const totalBytes = parts.reduce((sum, part) => sum + part.size, 0); + const parts: PendingPart[] = + session !== null && read !== null && packed + ? session.files.map((file, index) => { + const bytes = read[index]!; + return { + kind: "session" as const, + path: file.relPath, + size: bytes.length, + read: () => Promise.resolve(bytes), + }; + }) + : []; + const manifest = { + ...(session !== null && packed + ? { + session: { + driver: session.driver, + ...(session.cliVersion !== undefined ? { cliVersion: session.cliVersion } : {}), + cursor: session.cursor, + }, + } + : {}), + // Too large when it was sized, or when it was read: an unreadable + // session is simply left behind. + ...(session !== null && (!carriesSession || (read !== null && !packed)) + ? { sessionOmitted: "too_large" as const } + : {}), + }; + return { parts, manifest }; + }); +} +/** + * Writes the parts one after another to a temp payload, with each part's + * hash and the whole's. Null when a part changed size since it was sized + * (the packing runs again). + */ +function writePayload(dir: string, parts: ReadonlyArray) { + return Effect.gen(function* () { const payloadTemp = NodePath.join(dir, "payload.bin.tmp"); const whole = createHash("sha256"); let offset = 0; @@ -636,7 +756,6 @@ export function writeMoveExport( try { for (const part of parts) { const bytes = await part.read(); - // Changed since it was sized: pack it again. if (bytes.length !== part.size) { resized = true; break; @@ -659,66 +778,286 @@ export function writeMoveExport( await handle.close(); } }); - if (resized) return yield* new CheckoutChanged(); - const after = yield* checkoutFingerprint(git, root, afterDiffPath); - yield* fsCall("Couldn't tidy up.", async () => { - await NodeFs.rm(NodePath.join(dir, "bundle.tmp"), { force: true }); - await NodeFs.rm(diffPath, { force: true }); - await NodeFs.rm(afterDiffPath, { force: true }); - }); - if (after.key !== before.key) return yield* new CheckoutChanged(); + if (resized) return null; + return { table, totalBytes: offset, sha256: whole.digest("hex") }; + }); +} + +/** The manifest and the payload under their final names: a finished export is whole. */ +function writeManifest(dir: string, manifest: PeerMoveManifest) { + const manifestTemp = `${moveManifestPath(dir)}.tmp`; + return fsCall("Couldn't write the packed thread.", async () => { + await NodeFs.writeFile(manifestTemp, JSON.stringify(manifest)); + await NodeFs.rename(NodePath.join(dir, "payload.bin.tmp"), movePayloadPath(dir)); + await NodeFs.rename(manifestTemp, moveManifestPath(dir)); + }); +} + +/** At most this many files in a general chat's folder, as in any move. */ +const MOVE_MAX_FILES = 20_000; + +/** One file of a general chat's folder, as found. */ +interface ScratchEntry { + readonly path: string; + readonly absolute: string; + readonly kind: "file" | "symlink"; + readonly size: number; + readonly mtimeMs: number; + readonly executable: boolean; +} - const manifest: PeerMoveManifest = { - totalBytes, - sha256: whole.digest("hex"), - parts: table, +/** + * Every file under a general chat's folder (docs/design/fleet.md, Part 3e, + * (d)), with Part 3's rules for new files: regular files keep their + * executable bit, symbolic links go as their text, anything else refuses the + * move. A folder that was never made has no files. + */ +function listScratchFolder(folder: string) { + return Effect.gen(function* () { + const found: ScratchEntry[] = []; + const walk = async (relative: string): Promise => { + const absoluteDir = relative.length === 0 ? folder : NodePath.join(folder, relative); + let entries: Array; + try { + entries = await NodeFs.readdir(absoluteDir, { withFileTypes: true }); + } catch (error) { + if (relative.length === 0 && (error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; + } + for (const entry of entries.toSorted((left, right) => left.name.localeCompare(right.name))) { + const path = relative.length === 0 ? entry.name : `${relative}/${entry.name}`; + const absolute = NodePath.join(folder, path); + const stat = await NodeFs.lstat(absolute); + if (stat.isDirectory()) { + const refused = await walk(path); + if (refused !== null) return refused; + } else if (stat.isSymbolicLink()) { + const target = await NodeFs.readlink(absolute); + found.push({ + path, + absolute, + kind: "symlink", + size: Buffer.byteLength(target, "utf8"), + mtimeMs: stat.mtimeMs, + executable: false, + }); + } else if (stat.isFile()) { + found.push({ + path, + absolute, + kind: "file", + size: stat.size, + mtimeMs: stat.mtimeMs, + executable: (stat.mode & 0o111) !== 0, + }); + } else { + return `${path} isn't a regular file, so this chat can't move.`; + } + } + return null; + }; + const refused = yield* fsCall("Couldn't read this chat's folder.", () => walk("")); + if (refused !== null) return yield* fail(refused); + return found; + }); +} + +/** A listing's key: equal before and after packing means what was packed is what's there. */ +const scratchKey = (entries: ReadonlyArray) => + entries.map((entry) => `${entry.path}:${entry.kind}:${entry.size}:${entry.mtimeMs}`).join("\n"); + +/** Why a general chat's folder is too big to move, or null. */ +function scratchSizeRefusal(entries: ReadonlyArray): string | null { + const bytes = entries.reduce((sum, entry) => sum + entry.size, 0); + if (bytes > MOVE_MAX_BYTES) { + return `This chat's folder is ${Math.ceil(bytes / (1024 * 1024))} MB. Moves take up to 100 MB.`; + } + if (entries.length > MOVE_MAX_FILES) { + return `This chat's folder has ${entries.length.toLocaleString("en-US")} files. Moves take up to ${MOVE_MAX_FILES.toLocaleString("en-US")}.`; + } + return null; +} + +/** + * What the move dialog says of a general chat's folder: how many files and + * bytes, or why it can't move (too big, or a file that isn't one). + */ +export function summarizeScratchFolder(folder: string) { + return listScratchFolder(folder).pipe( + Effect.map((entries) => ({ + files: entries.length, + bytes: entries.reduce((sum, entry) => sum + entry.size, 0), + refusal: scratchSizeRefusal(entries), + })), + Effect.catch((failure) => + Effect.succeed({ files: 0, bytes: 0, refusal: failure.reason as string | null }), + ), + ); +} + +export interface ScratchExportInput { + readonly dir: string; + /** The chat's own folder (generalChatThreadScratchCwd). */ + readonly folder: string; + readonly attachmentsDir: string; + readonly thread: OrchestrationThread; + readonly source: MoveExportInput["source"]; + readonly agent: ModelSelection; + readonly nativeSession?: NativeSessionExport | null | undefined; + readonly state?: PeerMoveThreadState | undefined; +} + +/** + * Packs a General Chats thread (docs/design/fleet.md, Part 3e, (d)): every + * file in its folder, its attachments and its history, and its session. No + * bundle and no diff. The folder is listed before and after packing (path, + * size, time); a change means it packs once more, then gives up. + */ +export function writeScratchExport( + input: ScratchExportInput, +): Effect.Effect { + const attempt = Effect.gen(function* () { + yield* fsCall("Couldn't make room to pack this thread.", () => + NodeFs.mkdir(input.dir, { recursive: true }), + ); + const before = yield* listScratchFolder(input.folder); + const tooBig = scratchSizeRefusal(before); + if (tooBig !== null) return yield* fail(tooBig); + const parts: PendingPart[] = before.map((entry) => + entry.kind === "symlink" + ? { + kind: "file" as const, + path: entry.path, + mode: "symlink" as const, + size: entry.size, + read: async () => Buffer.from(await NodeFs.readlink(entry.absolute), "utf8"), + } + : { + kind: "file" as const, + path: entry.path, + mode: entry.executable ? ("executable" as const) : ("file" as const), + size: entry.size, + read: () => NodeFs.readFile(entry.absolute), + }, + ); + const history = exportThreadHistory(input.thread); + parts.push(...(yield* attachmentParts(history, input.attachmentsDir, input.state))); + const otherBytes = parts.reduce((sum, part) => sum + part.size, 0); + if (otherBytes > MOVE_MAX_BYTES) { + return yield* fail( + `This chat comes to ${Math.ceil(otherBytes / (1024 * 1024))} MB with its attachments. Moves carry at most 100 MB.`, + ); + } + const session = yield* sessionParts(input.nativeSession ?? null, otherBytes); + parts.push(...session.parts); + const payload = yield* writePayload(input.dir, parts); + if (payload === null) return yield* new CheckoutChanged(); + const after = yield* listScratchFolder(input.folder); + if (scratchKey(after) !== scratchKey(before)) return yield* new CheckoutChanged(); + const manifest: PeerMoveScratchManifest = { + workspace: "scratch", + totalBytes: payload.totalBytes, + sha256: payload.sha256, + parts: payload.table, source: input.source, - project: { - canonicalKey: input.canonicalKey, - subdirectory: input.subdirectory, - title: input.projectTitle, - }, - git: { headSha: checkout.headSha, branch: checkout.branch, baseSha: checkout.baseSha }, + project: { title: "General chats" }, thread: { title: input.thread.title, runtimeMode: input.thread.runtimeMode, interactionMode: input.thread.interactionMode, messages: history.messages, activities: history.activities, + ...(input.state !== undefined ? { state: input.state } : {}), }, agent: input.agent, - summary: { - messageCount: history.messages.length, - trackedFiles: tracked.length, - untrackedFiles: untracked.length, - unpushedCommits: checkout.unpushedCommits, - }, - ...(session !== null && sessionPacked - ? { - session: { - driver: session.driver, - ...(session.cliVersion !== undefined ? { cliVersion: session.cliVersion } : {}), - cursor: session.cursor, - }, - } - : {}), - // Too large when it was sized, or when it was read: an unreadable - // session is simply left behind. - ...(session !== null && (!carriesSession || (sessionBytesRead !== null && !sessionPacked)) - ? { sessionOmitted: "too_large" as const } - : {}), + summary: { messageCount: history.messages.length, files: before.length }, + ...session.manifest, }; - const manifestTemp = `${moveManifestPath(dir)}.tmp`; - yield* fsCall("Couldn't write the packed thread.", async () => { - await NodeFs.writeFile(manifestTemp, JSON.stringify(manifest)); - await NodeFs.rename(payloadTemp, movePayloadPath(dir)); - await NodeFs.rename(manifestTemp, moveManifestPath(dir)); - }); + yield* writeManifest(input.dir, manifest); return manifest; }); - const changedReason = "The checkout changed while this thread was being packed. Try again."; + const changedReason = "This chat's files changed while it was being packed. Try again."; return attempt.pipe( Effect.catchTag("CheckoutChanged", () => attempt), Effect.catchTag("CheckoutChanged", () => fail(changedReason)), ); } + +/** + * What a moved thread had going, as the manifest carries it (docs/design/ + * fleet.md, Part 3e), from what it carries (threadMoveCarry). Only for a + * computer that takes it. A goal that finished, or anything but working or + * paused, is never picked up, whatever the move's stop recorded. + */ +export function moveThreadStateOf(carry: ThreadMoveCarry): PeerMoveThreadState | undefined { + const goal = carry.goal; + const state: PeerMoveThreadState = { + ...(goal !== null + ? { + goal: { + objective: goal.objective, + status: goal.status, + tokenBudget: goal.tokenBudget, + tokensUsed: goal.tokensUsed, + timeUsedSeconds: goal.timeUsedSeconds, + createdAt: goal.createdAt, + updatedAt: goal.updatedAt, + ...(goal.checks !== undefined ? { checks: goal.checks } : {}), + ...(goal.lastCheck !== undefined ? { lastCheck: goal.lastCheck } : {}), + pickUp: carry.goalWorking && (goal.status === "active" || goal.status === "paused"), + }, + } + : {}), + ...(carry.checkBacks.length > 0 + ? { + checkBacks: carry.checkBacks.map((checkBack) => ({ + scheduledFor: checkBack.scheduledFor, + recurring: checkBack.recurring, + exact: checkBack.exact, + ...(checkBack.schedule !== undefined ? { schedule: checkBack.schedule } : {}), + ...(checkBack.cron !== undefined ? { cron: checkBack.cron } : {}), + ...(checkBack.description !== undefined ? { description: checkBack.description } : {}), + ...(checkBack.prompt !== undefined ? { prompt: checkBack.prompt } : {}), + durable: checkBack.durable, + })), + } + : {}), + ...(carry.pullRequests !== null + ? { + pullRequests: { + autoFix: carry.pullRequests.autoFix, + autoMerge: carry.pullRequests.autoMerge, + linked: carry.pullRequests.linked.map((entry) => ({ + number: entry.number, + url: entry.url, + autoFix: entry.autoFix, + autoMerge: entry.autoMerge, + })), + }, + } + : {}), + ...(carry.queuedFollowUps.length > 0 + ? { + queuedFollowUps: carry.queuedFollowUps.map((entry) => ({ + messageId: entry.messageId, + text: entry.text, + attachments: entry.attachments, + ...(entry.skills !== undefined ? { skills: entry.skills } : {}), + ...(entry.composer !== undefined ? { composer: entry.composer } : {}), + ...(entry.sentFrom !== undefined ? { sentFrom: entry.sentFrom } : {}), + interactionMode: entry.interactionMode, + createdAt: entry.createdAt, + })), + } + : {}), + ...(carry.proposedPlans.length > 0 + ? { + proposedPlans: carry.proposedPlans.map(({ eventSequence: _sequence, ...plan }) => plan), + } + : {}), + ...(carry.plansLeftBehind > 0 ? { plansLeftBehind: carry.plansLeftBehind } : {}), + }; + return Object.keys(state).length > 0 ? state : undefined; +} diff --git a/apps/server/src/moves/threadMoveView.ts b/apps/server/src/moves/threadMoveView.ts index c193cf474..85d1f2cd3 100644 --- a/apps/server/src/moves/threadMoveView.ts +++ b/apps/server/src/moves/threadMoveView.ts @@ -39,7 +39,11 @@ export const makeThreadMoveContextReader = Effect.gen(function* () { if (Option.isNone(found)) return null; const thread = found.value; const project = yield* projectOf(thread.projectId); - const checkout = thread.worktreePath ?? project?.workspaceRoot ?? null; + // A general chat works in a folder of its own: it shares no checkout. + const checkout = + project?.kind === "general-chat" + ? null + : (thread.worktreePath ?? project?.workspaceRoot ?? null); // Its attached children, and every other thread in the same checkout. const neighbors = yield* sql<{ readonly threadId: ThreadId }>` SELECT t.thread_id AS "threadId" diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 6f6da82e0..c0e4f7331 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -149,6 +149,7 @@ function createProviderServiceHarness( compactContext: () => unsupported(), setThreadGoal: () => unsupported(), pauseThreadGoalForStop: () => unsupported(), + getThreadGoal: () => Effect.succeed(null), clearThreadGoal: () => unsupported(), respondToRequest: () => unsupported(), respondToUserInput: () => unsupported(), diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index b23630079..ce5eba171 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2646,6 +2646,120 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { }), ); + it.effect( + "keeps what a move owes back, and the message it wrote for the agent, in every read", + () => + Effect.gen(function* () { + const engine = yield* OrchestrationEngineService; + const snapshots = yield* ProjectionSnapshotQuery; + const createdAt = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-move-restore"); + const requestId = ThreadMoveRequestId.make("request-move-restore"); + const target = { environmentId: EnvironmentId.make("environment-pc"), label: "Windows PC" }; + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.make("cmd-move-restore-project"), + projectId: ProjectId.make("project-move-restore"), + title: "Move Restore", + workspaceRoot: "/tmp/project-move-restore", + createdAt, + }); + yield* engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-move-restore-thread"), + threadId, + projectId: ProjectId.make("project-move-restore"), + title: "Move me", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: "default", + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt, + }); + const goal = { + threadId, + objective: "Make the suite pass", + status: "active" as const, + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt, + updatedAt: createdAt, + }; + yield* engine.dispatch({ + type: "thread.goal.state.set", + commandId: CommandId.make("cmd-move-restore-goal"), + threadId, + goal, + createdAt, + }); + yield* engine.dispatch({ + type: "thread.move.queue", + commandId: CommandId.make("cmd-move-restore-queue"), + threadId, + requestId, + target, + mode: "stop-now", + requestedBy: { kind: "user" }, + targetTakes: { threadState: true }, + createdAt, + }); + yield* engine.dispatch({ + type: "thread.move.unqueue", + commandId: CommandId.make("cmd-move-restore-unqueue"), + threadId, + requestId, + createdAt: "2026-01-01T00:00:01.000Z", + }); + const owed = Option.getOrThrow( + yield* snapshots.getThreadDetailById(threadId), + ).moveRestoreOwed; + assert.deepEqual(owed, { + target, + interrupted: { goalActive: true }, + at: "2026-01-01T00:00:01.000Z", + }); + // What the decider reads after a restart: the same record. + const model = yield* snapshots.getCommandReadModel(); + assert.deepEqual( + model.threads.find((thread) => thread.id === threadId)?.moveRestoreOwed, + owed, + ); + + yield* engine.dispatch({ + type: "thread.move.restore", + commandId: CommandId.make("cmd-move-restore-pay"), + threadId, + at: owed!.at, + message: { messageId: MessageId.make("m-put-back"), text: "The move didn't happen." }, + createdAt: "2026-01-01T00:00:02.000Z", + }); + const paid = Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)); + assert.equal(paid.queuedFollowUps?.[0]?.afterMove, true); + assert.deepInclude(paid.moveRestoreOwed, { goalOwed: true }); + yield* engine.dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-move-restore-send"), + threadId, + messageId: MessageId.make("m-put-back"), + createdAt: "2026-01-01T00:00:03.000Z", + }); + const sent = Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)); + assert.equal(sent.messages.find((message) => message.id === "m-put-back")?.afterMove, true); + yield* engine.dispatch({ + type: "thread.move.restore", + commandId: CommandId.make("cmd-move-restore-goal-given"), + threadId, + at: owed!.at, + finished: true, + createdAt: "2026-01-01T00:00:04.000Z", + }); + const done = Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)); + assert.equal(done.moveRestoreOwed ?? null, null); + }), + ); + it.effect("projects persist updated scripts from project.meta.update", () => Effect.gen(function* () { const engine = yield* OrchestrationEngineService; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 8765afafd..a12e1df4f 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -43,6 +43,7 @@ import { import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts"; import { 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"; import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts"; @@ -658,6 +659,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } + case "thread.move-restore-set": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) return; + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + moveRestoreOwed: event.payload.moveRestoreOwed, + }); + return; + } + case "thread.history-seed-delivered": { const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, @@ -1271,12 +1284,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti const { followUp } = event.payload; yield* projectionThreadRepository.upsert({ ...existingRow.value, - queuedFollowUps: [ - ...(existingRow.value.queuedFollowUps ?? []).filter( - (queued) => queued.messageId !== followUp.messageId, - ), - followUp, - ], + queuedFollowUps: withQueuedFollowUp(existingRow.value.queuedFollowUps ?? [], followUp), updatedAt: event.occurredAt, }); return; @@ -1645,6 +1653,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...(event.payload.composer !== undefined ? { composer: event.payload.composer } : {}), ...(event.payload.sentFrom !== undefined ? { sentFrom: event.payload.sentFrom } : {}), ...(event.payload.trigger !== undefined ? { trigger: event.payload.trigger } : {}), + ...(event.payload.afterMove === true ? { afterMove: true as const } : {}), isStreaming: event.payload.streaming, createdAt: previousMessage?.createdAt ?? event.payload.createdAt, updatedAt: event.payload.updatedAt, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 188f93492..fe7275c77 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -66,6 +66,7 @@ import { ThreadPendingMove, ThreadMovedFrom, ThreadMoveOutcome, + ThreadMoveRestore, ThreadRemoteOrigin, ThreadScheduledRun, ThreadWorktreeOrigin, @@ -182,6 +183,7 @@ type ThreadLineageRow = Pick< | "pendingMove" | "movedFrom" | "lastMoveOutcome" + | "moveRestoreOwed" | "historySeedOwed" | "historySeedMessageId" | "nativeSession" @@ -203,6 +205,8 @@ const threadLineageFields = (row: ThreadLineageRow) => ({ ...(row.outsideOrigin ? { outsideOrigin: row.outsideOrigin } : {}), ...(row.outsideWork && row.outsideWork.length > 0 ? { outsideWork: row.outsideWork } : {}), ...threadMoveFields(row), + // What a move that didn't happen owes back: the server's alone, never on a shell. + ...(row.moveRestoreOwed ? { moveRestoreOwed: row.moveRestoreOwed } : {}), ...((row.historySeedOwed ?? 0) > 0 ? { historySeedOwed: true } : {}), ...(row.historySeedMessageId ? { historySeedMessageId: row.historySeedMessageId } : {}), ...(row.nativeSession ? { nativeSession: row.nativeSession } : {}), @@ -274,6 +278,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( sentFrom: Schema.NullOr(Schema.fromJsonString(MessageSentFrom)), trigger: Schema.NullOr(MessageTrigger), notSent: Schema.NullOr(Schema.Number), + afterMove: Schema.optional(Schema.NullOr(Schema.Number)), }), ); const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan.mapFields( @@ -319,6 +324,7 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( pendingMove: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadPendingMove))), movedFrom: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMovedFrom))), lastMoveOutcome: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMoveOutcome))), + moveRestoreOwed: Schema.optional(Schema.NullOr(Schema.fromJsonString(ThreadMoveRestore))), }), ); const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields( @@ -655,6 +661,7 @@ function mapThreadMessageRow( ...(row.sentFrom !== null ? { sentFrom: row.sentFrom } : {}), ...(row.trigger !== null ? { trigger: row.trigger } : {}), ...(row.notSent === 1 ? { notSent: true as const } : {}), + ...(row.afterMove === 1 ? { afterMove: true as const } : {}), turnId: row.turnId, streaming: row.isStreaming === 1, createdAt: row.createdAt, @@ -966,6 +973,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1037,6 +1045,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1110,6 +1119,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1160,6 +1170,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sent_from AS "sentFrom", message_trigger AS "trigger", not_sent AS "notSent", + after_move AS "afterMove", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -1221,6 +1232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sent_from AS "sentFrom", message_trigger AS "trigger", not_sent AS "notSent", + after_move AS "afterMove", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -1948,6 +1960,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -1995,6 +2008,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sent_from AS "sentFrom", message_trigger AS "trigger", not_sent AS "notSent", + after_move AS "afterMove", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -3781,6 +3795,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index af64a4f41..e6df0bb1c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -8,6 +8,7 @@ import { CommandRequestId, CommandRunId, EnvironmentId, + ThreadMoveRequestId, ModelSelection, type MessageSentFrom, type OrchestrationCommand, @@ -417,6 +418,11 @@ describe("ProviderCommandReactor", () => { const pauseThreadGoalForStop = vi.fn(() => Effect.succeed(null), ); + // The goal the provider holds; tests that move a thread set it. + let heldGoal: Effect.Success> = null; + const getThreadGoal = vi.fn(() => + Effect.sync(() => heldGoal), + ); const respondToRequest = vi.fn(() => Effect.void); const respondToUserInput = vi.fn(() => Effect.void); const stopSession = vi.fn((input: unknown) => @@ -551,6 +557,7 @@ describe("ProviderCommandReactor", () => { compactContext, setThreadGoal: setThreadGoal as ProviderServiceShape["setThreadGoal"], pauseThreadGoalForStop, + getThreadGoal, clearThreadGoal: clearThreadGoal as ProviderServiceShape["clearThreadGoal"], respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"], respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"], @@ -802,6 +809,10 @@ describe("ProviderCommandReactor", () => { compactContext, setThreadGoal, pauseThreadGoalForStop, + getThreadGoal, + setHeldGoal: (goal: typeof heldGoal) => { + heldGoal = goal; + }, clearThreadGoal, respondToRequest, respondToUserInput, @@ -5348,6 +5359,277 @@ describe("ProviderCommandReactor", () => { }), ); + describe("a thread that moves with what it had going (fleet.md, Part 3e)", () => { + const MOVED = ThreadId.make("thread-moved-here"); + const at = "2026-01-01T00:00:00.000Z"; + const sessionOf = ( + harness: Awaited>, + id: ThreadId, + status: "running" | "ready", + stamp: string, + ) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-moved-session-${id}-${status}-${stamp}`), + threadId: id, + session: { + threadId: id, + status, + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + runtimeMode: "approval-required", + activeTurnId: status === "running" ? asTurnId(`turn-${stamp}`) : null, + pendingBackgroundTaskCount: 0, + lastError: null, + updatedAt: stamp, + }, + createdAt: stamp, + }), + ); + const queued = (id: string, extra?: Record) => ({ + messageId: asMessageId(id), + text: `message ${id}`, + attachments: [], + runtimeMode: "approval-required" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at, + ...extra, + }); + + it("a queue waits while its thread waits to move: the turn's end sends nothing", async () => { + const harness = await createHarness(); + await setSession(harness, "running", "2026-01-01T00:00:01.000Z"); + await submit(harness, { + messageId: asMessageId("q-wait"), + text: "then this", + delivery: "queue", + }); + await waitFor(async () => (await readThread(harness))?.queuedFollowUps?.length === 1); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.move.queue", + commandId: CommandId.make("cmd-move-queue-wait"), + threadId, + requestId: ThreadMoveRequestId.make("request-wait"), + target: { environmentId: EnvironmentId.make("env-mac"), label: "Mac mini" }, + mode: "when-done", + requestedBy: { kind: "user" }, + targetTakes: { threadState: true }, + createdAt: "2026-01-01T00:00:02.500Z", + }), + ); + await setSession(harness, "ready", "2026-01-01T00:00:03.000Z"); + await harness.drain(); + expect(harness.sendTurn).not.toHaveBeenCalled(); + expect( + (await readThread(harness))?.queuedFollowUps?.map((entry) => entry.messageId), + ).toEqual(["q-wait"]); + }); + + it("an import's queue goes by its kick alone, and its goal reaches the provider once the queue is through", async () => { + const harness = await createHarness(); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.import", + commandId: CommandId.make("cmd-import-moved"), + threadId: MOVED, + projectId: asProjectId("project-1"), + title: "Make the suite pass", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + movedFrom: { + environmentId: EnvironmentId.make("env-windows"), + label: "Windows PC", + threadId: ThreadId.make("thread-there"), + movedAt: at, + }, + messages: [], + activities: [], + goal: { + threadId: MOVED, + objective: "Make the suite pass", + status: "active", + tokenBudget: 5_000, + tokensUsed: 1_200, + timeUsedSeconds: 60, + createdAt: at, + updatedAt: at, + }, + queuedFollowUps: [queued("q-moved")], + arrival: { + message: { messageId: asMessageId("m-arrival"), text: "This thread moved." }, + brought: ["its goal", "1 queued message"], + left: [], + }, + createdAt: at, + }), + ); + await harness.drain(); + // Its own events send nothing. + expect(harness.sendTurn).not.toHaveBeenCalled(); + + // The move's kick: the arrival message, first. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-arrive-moved"), + threadId: MOVED, + messageId: asMessageId("m-arrival"), + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ messageId: "m-arrival" }); + const arrived = (await harness.readModel()).threads.find((entry) => entry.id === MOVED); + expect(arrived?.messages.find((entry) => entry.id === "m-arrival")?.afterMove).toBe(true); + + // Its turn ends: the user's queued message goes next, the goal not yet. + await sessionOf(harness, MOVED, "running", "2026-01-01T00:00:02.000Z"); + await sessionOf(harness, MOVED, "ready", "2026-01-01T00:00:03.000Z"); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ messageId: "q-moved" }); + expect(harness.setThreadGoal).not.toHaveBeenCalled(); + + // That one ends with nothing left: the provider holds no goal, so it is + // given the goal, with what is left of its budget. + await sessionOf(harness, MOVED, "running", "2026-01-01T00:00:04.000Z"); + await sessionOf(harness, MOVED, "ready", "2026-01-01T00:00:05.000Z"); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 1); + expect(harness.setThreadGoal.mock.calls[0]?.[0]).toMatchObject({ + threadId: MOVED, + objective: "Make the suite pass", + status: "active", + tokenBudget: 3_800, + }); + + // Once the provider holds it working, a later turn's end gives nothing more. + harness.setHeldGoal({ + objective: "Make the suite pass", + status: "active", + tokenBudget: 3_800, + tokensUsed: 10, + timeUsedSeconds: 1, + createdAt: at, + updatedAt: at, + }); + await sessionOf(harness, MOVED, "running", "2026-01-01T00:00:06.000Z"); + await sessionOf(harness, MOVED, "ready", "2026-01-01T00:00:07.000Z"); + await harness.drain(); + expect(harness.setThreadGoal).toHaveBeenCalledTimes(1); + }); + + it("a goal put back after a dropped move works again once its message went, even if the stop paused it late", async () => { + const harness = await createHarness(); + const goal = (status: "active" | "paused") => ({ + threadId, + objective: "Keep the suite green", + status, + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: at, + updatedAt: at, + }); + const dispatch = (command: Record) => + Effect.runPromise(harness.engine.dispatch(command as never)); + await dispatch({ + type: "thread.goal.state.set", + commandId: CommandId.make("cmd-put-back-goal"), + threadId, + goal: goal("active"), + createdAt: at, + }); + const requestId = ThreadMoveRequestId.make("request-put-back"); + await dispatch({ + type: "thread.move.queue", + commandId: CommandId.make("cmd-put-back-queue"), + threadId, + requestId, + target: { environmentId: EnvironmentId.make("env-mac"), label: "Mac mini" }, + mode: "stop-now", + requestedBy: { kind: "user" }, + targetTakes: { threadState: true }, + createdAt: at, + }); + await dispatch({ + type: "thread.move.unqueue", + commandId: CommandId.make("cmd-put-back-unqueue"), + threadId, + requestId, + createdAt: "2026-01-01T00:00:01.000Z", + }); + const owedAt = (await readThread(harness))?.moveRestoreOwed?.at; + expect(owedAt).toBeDefined(); + await dispatch({ + type: "thread.move.restore", + commandId: CommandId.make("cmd-put-back-pay"), + threadId, + at: owedAt, + message: { messageId: asMessageId("m-put-back"), text: "The move didn't happen." }, + createdAt: "2026-01-01T00:00:02.000Z", + }); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ messageId: "m-put-back" }); + // The move's stop paused it only now (its pause answered late). + await dispatch({ + type: "thread.goal.state.set", + commandId: CommandId.make("cmd-put-back-late-pause"), + threadId, + goal: goal("paused"), + createdAt: "2026-01-01T00:00:03.000Z", + }); + await setSession(harness, "running", "2026-01-01T00:00:04.000Z"); + await setSession(harness, "ready", "2026-01-01T00:00:05.000Z"); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 1); + expect(harness.setThreadGoal.mock.calls[0]?.[0]).toMatchObject({ + objective: "Keep the suite green", + status: "active", + }); + await waitFor(async () => ((await readThread(harness))?.moveRestoreOwed ?? null) === null); + }); + + it("Resume on a session whose provider holds no goal gives it the goal the thread reads", async () => { + const harness = await createHarness(); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.goal.state.set", + commandId: CommandId.make("cmd-goal-paused-here"), + threadId, + goal: { + threadId, + objective: "Keep the suite green", + status: "paused", + tokenBudget: 10_000, + tokensUsed: 4_000, + timeUsedSeconds: 30, + createdAt: at, + updatedAt: at, + }, + createdAt: at, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.goal.set", + commandId: CommandId.make("cmd-goal-resume-here"), + threadId, + status: "active", + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 1); + expect(harness.setThreadGoal.mock.calls[0]?.[0]).toMatchObject({ + objective: "Keep the suite green", + status: "active", + tokenBudget: 6_000, + }); + }); + }); + it("sends a queued message as the next turn once the running turn completes", async () => { const harness = await createHarness(); const first = asMessageId("queued-first"); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 4954cd6bc..a3e79fa8e 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -83,6 +83,7 @@ import * as DateTime from "effect/DateTime"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Equal from "effect/Equal"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -157,6 +158,7 @@ import { inviteAnswerRefusal } from "../agentInvites.ts"; import { handOffReplyText } from "../agentRequestDecisions.ts"; import { isCancelledReport } from "../childThreadDecisions.ts"; import { NO_BACKGROUND_TASKS } from "../sessionBackgroundTasks.ts"; +import { isRestorePaid } from "../threadMoveDecisions.ts"; import { SideAnswerStartError } from "../Errors.ts"; const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError); const isProviderAdapterValidationError = Schema.is(ProviderAdapterValidationError); @@ -438,6 +440,14 @@ const PROVIDER_INTERRUPT_ACK_TIMEOUT = Duration.seconds(10); const TURN_PREPARATION_TIMEOUT = Duration.seconds(90); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); +/** + * Whether a thread's queue waits for its move (docs/design/fleet.md, Part + * 3e, (e)): while a move waits, sending it would keep the thread from ever + * being free; once it moves, its queue went with it. + */ +const queueWaitsForMove = (thread: Pick) => + (thread.pendingMove ?? null) !== null || (thread.move ?? null) !== null; + const decodeFellBackPayload = Schema.decodeUnknownOption(ThreadNativeSessionFellBackPayload); /** A carried session fell back, and its refused message couldn't go again on its own. */ @@ -3954,17 +3964,35 @@ const make = Effect.gen(function* () { } }), ), + // A resume (status only) on a session whose provider holds no goal + // (a moved thread's, or one whose session started fresh) carries the + // goal the thread reads, with what is left of its budget: alone it + // would fail on Claude and do nothing on Codex. Effect.flatMap(() => + event.payload.objective === undefined && + event.payload.status === "active" && + thread.goal !== null + ? providerService.getThreadGoal({ threadId: goalHolderSessionKey }).pipe( + Effect.map((held) => (held === null ? thread.goal : null)), + Effect.orElseSucceed(() => null), + ) + : Effect.succeed(null), + ), + Effect.flatMap((resumed) => providerService.setThreadGoal({ threadId: goalHolderSessionKey, modelSelection: goalModelSelection, ...(event.payload.objective !== undefined ? { objective: event.payload.objective } - : {}), + : resumed !== null + ? { objective: resumed.objective } + : {}), ...(event.payload.status !== undefined ? { status: event.payload.status } : {}), ...(event.payload.tokenBudget !== undefined ? { tokenBudget: event.payload.tokenBudget } - : {}), + : resumed !== null && resumed.tokenBudget !== null + ? { tokenBudget: Math.max(1, resumed.tokenBudget - resumed.tokensUsed) } + : {}), }), ), Effect.asVoid, @@ -5586,6 +5614,11 @@ const make = Effect.gen(function* () { const processFollowUpQueued = Effect.fn("processFollowUpQueued")(function* ( event: Extract, ) { + // A moved thread's queue, written by its import: the move's own kick + // sends its head (docs/design/fleet.md, Part 3e), so nothing goes twice. + if (event.payload.imported === true) { + return; + } // A message the user sent after Stop means they are moving on. One an // agent queued (in this thread, or from another thread) never does. const fromUser = !isAgentOrigin(event.payload.followUp); @@ -5599,6 +5632,10 @@ const make = Effect.gen(function* () { if (!thread) { return; } + // While a move waits or runs the queue waits too, or the thread never gets free. + if (queueWaitsForMove(thread)) { + return; + } if (status === "running" || status === "starting") { // A reply or a report for the agent at work goes into its turn now, and // so does the user's message that overtook a continue already sent. @@ -5643,6 +5680,89 @@ const make = Effect.gen(function* () { yield* sendQueuedFollowUp(threadId, messageId, createdAt); }); + /** + * A moved thread's goal, or one a move that didn't happen put back, reaches + * the provider after the conversation does (docs/design/fleet.md, Part 3e, + * "Arrival"): once a turn ends with nothing left in the queue, a goal the + * thread reads as working that the provider doesn't hold as working is + * given to it, with what is left of its budget. Given only after the + * message that told the agent, never while a turn runs (a Claude `/goal` + * cuts a running turn short; whether Codex takes one mid-turn is + * unverified), and again after a carried session fell back to a fresh one. + * Only threads that moved here, or owe it back: nothing for any other. + */ + const giveGoalAfterMove = Effect.fnUntraced(function* ( + thread: OrchestrationThread, + createdAt: string, + ) { + const owed = thread.moveRestoreOwed ?? null; + // A put-back paid but for its last steps: its message went and the queue is through. + const finishing = owed !== null && isRestorePaid(owed); + const owesGoal = finishing && owed?.goalOwed === true; + if ((thread.movedFrom ?? null) === null && !finishing) return; + if ((thread.queuedFollowUps ?? []).length > 0) return; + // Rooms can't move: the thread's own agent holds its goal. + if (sessionSlotParticipantId(thread.session) !== null) return; + const goal = thread.goal; + // A goal put back reads paused when the move's stop paused it after the + // put-back read it (Codex): it was working, so it works again. + if (goal !== null && (goal.status === "active" || (owesGoal && goal.status === "paused"))) { + const held = yield* providerService + .getThreadGoal({ threadId: thread.id }) + .pipe(Effect.option); + // Unreadable: tried again at the next turn end. + if (Option.isNone(held)) return; + if (held.value === null || held.value.status !== "active") { + const given = yield* providerService + .setThreadGoal({ + threadId: thread.id, + modelSelection: thread.modelSelection, + status: "active", + // The provider counts from zero again: what is left of the budget. + ...(held.value === null + ? { + objective: goal.objective, + ...(goal.tokenBudget !== null + ? { tokenBudget: Math.max(1, goal.tokenBudget - goal.tokensUsed) } + : {}), + } + : {}), + }) + .pipe(Effect.exit); + if (Exit.isFailure(given)) { + yield* appendProviderFailureActivity({ + threadId: thread.id, + kind: "provider.goal.failed", + summary: "Goal update failed", + detail: formatFailureDetail(given.cause), + turnId: null, + createdAt, + }); + return; + } + } + } + if (finishing && owed !== null) { + yield* orchestrationEngine + .dispatch({ + type: "thread.move.restore", + commandId: serverCommandId("move-restore-finished"), + threadId: thread.id, + at: owed.at, + finished: true, + createdAt, + }) + .pipe( + Effect.catch((error) => + Effect.logInfo("provider command reactor: a put-back goal wasn't recorded", { + threadId: thread.id, + detail: String(error), + }), + ), + ); + } + }); + const maybeSendNextQueuedFollowUp = Effect.fnUntraced(function* ( event: Extract, ) { @@ -5703,6 +5823,13 @@ const make = Effect.gen(function* () { return; } const thread = yield* resolveThread(threadId); + // A turn that ended while a move waits is what the move waited for. + if (thread !== undefined && queueWaitsForMove(thread)) { + return; + } + if (turnFinished && thread !== undefined) { + yield* giveGoalAfterMove(thread, event.occurredAt); + } const next = thread ? nextQueuedFollowUp(thread) : undefined; if (!thread || !next) { return; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 9d5629848..af22e7e08 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -144,6 +144,7 @@ function createProviderServiceHarness() { compactContext: () => unsupported(), setThreadGoal: () => unsupported(), pauseThreadGoalForStop: () => unsupported(), + getThreadGoal: () => Effect.succeed(null), clearThreadGoal: () => unsupported(), respondToRequest: () => unsupported(), respondToUserInput: () => unsupported(), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 98ba75a35..72a48e77a 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -2733,12 +2733,17 @@ const make = Effect.gen(function* () { createdAt: event.createdAt, }); } + // A move's stop ends them on purpose: it carries them (docs/design/fleet.md, Part 3e, (b)). + const movingTo = (thread.pendingMove ?? thread.move ?? null)?.target.label; for (const [index, ended] of (event.payload.ended ?? []).entries()) { yield* appendCheckBackActivity({ event, threadId: thread.id, kind: "check-back.ended", - summary: "Check-back cancelled", + summary: + movingTo !== undefined + ? `Check-back ended: this thread is moving to ${movingTo}` + : "Check-back cancelled", tag: `check-back-ended-${index}`, payload: { scheduledFor: ended.scheduledFor, diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts index 142c15e72..31c6495d5 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts @@ -1,10 +1,13 @@ import { CommandId, + EnvironmentId, EventId, MessageId, ProjectId, ProviderInstanceId, ThreadId, + ThreadMoveId, + ThreadMoveRequestId, TurnId, type OrchestrationCommand, type OrchestrationEvent, @@ -45,6 +48,11 @@ import { type ProjectionSnapshotQueryShape, } from "../Services/ProjectionSnapshotQuery.ts"; import { PullRequestAutomationWatcher } from "../Services/PullRequestAutomationWatcher.ts"; +import { + makeThreadActionGate, + ThreadActionGate, + type ThreadActionGateShape, +} from "../../moves/ThreadActionGate.ts"; import { makePullRequestAutomationWatcherLive } from "./PullRequestAutomationWatcher.ts"; const NOW_ISO = "2026-05-04T10:00:00.000Z"; @@ -461,6 +469,8 @@ describe("PullRequestAutomationWatcher", () => { readonly holdStatusRead?: (cwd: string) => Promise | undefined; /** Runs as the watcher picks an event up, just before it acts on it. */ readonly onEventHeard?: () => void; + /** The gate the watcher shares with moves; its own when absent. */ + readonly gate?: ThreadActionGateShape; }) { let script = input.script; let threads = input.threads; @@ -598,6 +608,7 @@ describe("PullRequestAutomationWatcher", () => { }), ), Layer.provideMerge(Layer.succeed(PullRequestService, pullRequestService)), + Layer.provideMerge(Layer.succeed(ThreadActionGate, input.gate ?? makeThreadActionGate())), ); runtime = ManagedRuntime.make(layer); const watcher = await runtime.runPromise(Effect.service(PullRequestAutomationWatcher)); @@ -1553,6 +1564,136 @@ describe("PullRequestAutomationWatcher", () => { describe("merge when checks pass", () => { const armed = thread({ pullRequestAutoFix: false, pullRequestAutoMerge: "rebase" }); + describe("a thread that moves to another computer (fleet.md, Part 3e)", () => { + const moving = { + transferId: ThreadMoveId.make("transfer-1"), + target: { environmentId: EnvironmentId.make("environment-mac-mini"), label: "Mac mini" }, + agent: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" }, + phase: "exporting" as const, + cancelRequested: false, + startedAt: NOW_ISO, + }; + const waiting = { + requestId: ThreadMoveRequestId.make("request-1"), + target: moving.target, + mode: "when-done" as const, + stage: "waiting" as const, + requestedAt: NOW_ISO, + requestedBy: { kind: "user" as const }, + }; + + it("is never looked at, nor merged, while it waits to move, moves, or once it moved", async () => { + for (const state of [ + { pendingMove: waiting }, + { move: moving }, + { + move: { ...moving, movedAway: { threadId: ThreadId.make("there"), movedAt: NOW_ISO } }, + }, + ]) { + const { actions, commands, statusReads, sweep } = await createHarness({ + threads: [{ ...armed, ...state }], + script: { + remote: OPEN_PULL_REQUEST, + detail: mergeable([PASSING_CHECK]), + activity: activity(), + merge: () => Effect.succeed({ state: "merged" }), + }, + }); + await sweep(); + // No look at all: no read of its checkout, so no baseline step either. + expect(statusReads).toEqual([]); + expect(actions).toEqual([]); + expect(commands).toEqual([]); + } + }); + + it("does not merge once the thread froze for its move while the host was being read", async () => { + const gate = makeThreadActionGate(); + let freeze = () => {}; + const order: string[] = []; + const { actions, setThreads, sweep } = await createHarness({ + threads: [armed], + gate, + script: { + remote: OPEN_PULL_REQUEST, + get detail() { + freeze(); + return mergeable([PASSING_CHECK]); + }, + activity: activity(), + merge: () => Effect.succeed({ state: "merged" }), + }, + }); + // The move takes the gate around its freeze, just as the watcher + // decides to merge: the watcher waits for it, then reads the thread + // as moving and stands down. + let frozen: Promise = Promise.resolve(); + freeze = () => { + freeze = () => {}; + frozen = Effect.runPromise( + gate.withThread( + THREAD_ID, + Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50))).pipe( + Effect.andThen( + Effect.sync(() => { + setThreads([{ ...armed, move: moving }]); + order.push("frozen"); + }), + ), + ), + ), + ); + }; + await sweep(); + await frozen; + expect(order).toEqual(["frozen"]); + expect(actions).toEqual([]); + }); + + it("a merge already under way finishes before the freeze, which waits for it", async () => { + const gate = makeThreadActionGate(); + const order: string[] = []; + let letMergeFinish = () => {}; + const mergeHeld = new Promise((resolve) => { + letMergeFinish = resolve; + }); + let mergeStarted = () => {}; + const started = new Promise((resolve) => { + mergeStarted = resolve; + }); + const { actions, sweep } = await createHarness({ + threads: [armed], + gate, + script: { + remote: OPEN_PULL_REQUEST, + detail: mergeable([PASSING_CHECK]), + activity: activity(), + merge: () => + Effect.promise(async () => { + mergeStarted(); + await mergeHeld; + order.push("merged"); + return { state: "merged" as const }; + }), + }, + }); + const sweeping = sweep(); + await started; + const freezing = Effect.runPromise( + gate.withThread( + THREAD_ID, + Effect.sync(() => order.push("frozen")), + ), + ); + await new Promise((resolve) => setTimeout(resolve, 30)); + expect(order).toEqual([]); + letMergeFinish(); + await Promise.all([sweeping, freezing]); + expect(order).toEqual(["merged", "frozen"]); + expect(actions.map((action) => action.action)).toEqual(["merge"]); + }); + }); + it("waits for checks and pushes, then merges once and turns itself off", async () => { const { actions, commands, setScript, sweep } = await createHarness({ threads: [armed], diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts index 958f7d472..cedead440 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts @@ -59,6 +59,7 @@ import * as Schema from "effect/Schema"; import { forkPullRequestBranchPrefix, GitManager } from "../../git/GitManager.ts"; import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; +import { ThreadActionGate } from "../../moves/ThreadActionGate.ts"; import { PullRequestService } from "../../pullRequest/PullRequestService.ts"; import type { GitWorktreeEntry } from "../../vcs/GitVcsDriver.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; @@ -260,12 +261,24 @@ function isSamePullRequest(left: string, right: string): boolean { return normalize(left) === normalize(right); } +/** + * Whether the thread is moving to another computer, or waits to (docs/ + * design/fleet.md, Part 3e, (c)): nothing here acts for it then, not a look, + * a baseline step, a turn or a merge. One that moved lives there now. + */ +function isMoving(thread: Pick): boolean { + return (thread.pendingMove ?? null) !== null || (thread.move ?? null) !== null; +} + /** * Whether the watcher has anything to do for a thread's pull requests: fixing - * or merging its own or one it holds by number. An archived thread has nothing. + * or merging its own or one it holds by number. An archived thread has + * nothing, and neither has one that moves (isMoving). */ function isWatched(thread: OrchestrationThreadShell): boolean { - return threadPullRequestAutomationArmed(thread) && thread.archivedAt === null; + return ( + threadPullRequestAutomationArmed(thread) && thread.archivedAt === null && !isMoving(thread) + ); } /** @@ -422,6 +435,9 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher const gitManager = yield* GitManager; const gitWorkflow = yield* GitWorkflowService; const pullRequestService = yield* PullRequestService; + // Shared with the move: an act holds it from the read that decides it + // through the act, so a freeze lands before it or after it, never during. + const actionGate = yield* ThreadActionGate; const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS); const inMotionIntervalMs = Math.max( @@ -780,34 +796,43 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher // one means "not now", so the thread is read again just before a merge // that cannot be taken back. Background work the agent left running // does not: see `hasWorkInProgress`. - const latest = yield* attempt( - "thread-read", - thread.id, - projectionSnapshotQuery.getThreadShellById(thread.id), - ); - if ( - latest === null || - Option.isNone(latest) || - mergeSwitchOf(latest.value, number, input.holders) === null || - awaitsAgentOrUser(latest.value) - ) { - return false; - } - // The method the user chose, unless the repository has since stopped // allowing it; then the host's own first choice. const mergeMethod = detail.mergeMethods.includes(input.mergeMethod) ? input.mergeMethod : detail.mergeMethods[0]; - const outcome = yield* Effect.exit( - pullRequestService.runAction({ - projectId: input.reference.projectId, - repository: input.reference.repository, - number, - action: "merge", - ...(mergeMethod === undefined ? {} : { mergeMethod }), + // A move under way, or waiting, means not here either. + const outcome = yield* actionGate.withThread( + thread.id, + Effect.gen(function* () { + const latest = yield* attempt( + "thread-read", + thread.id, + projectionSnapshotQuery.getThreadShellById(thread.id), + ); + if ( + latest === null || + Option.isNone(latest) || + isMoving(latest.value) || + mergeSwitchOf(latest.value, number, input.holders) === null || + awaitsAgentOrUser(latest.value) + ) { + return null; + } + return yield* Effect.exit( + pullRequestService.runAction({ + projectId: input.reference.projectId, + repository: input.reference.repository, + number, + action: "merge", + ...(mergeMethod === undefined ? {} : { mergeMethod }), + }), + ); }), ); + if (outcome === null) { + return false; + } const landing = Exit.isSuccess(outcome) && outcome.value.state === "merged" ? "merged" @@ -918,37 +943,47 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher // before the host is asked. The agent has looked once a turn asked // for since the hand-off has completed; one stopped or failed has not, // and a time that does not parse proves nothing either way. - const latest = yield* attempt( - "thread-read", + const acted = yield* actionGate.withThread( input.threadId, - projectionSnapshotQuery.getThreadShellById(input.threadId), - ); - if (latest === null || Option.isNone(latest)) { - return; - } - const thread = latest.value; - const turn = thread.latestTurn; - const lookedSince = - turn !== null && - turn.state === "completed" && - Date.parse(turn.requestedAt) >= Date.parse(pending.requestedAt); - if ( - !fixSwitchOn(thread, number, input.holders) || - hasWorkInProgress(thread) || - !lookedSince - ) { - return; - } + Effect.gen(function* () { + const latest = yield* attempt( + "thread-read", + input.threadId, + projectionSnapshotQuery.getThreadShellById(input.threadId), + ); + if (latest === null || Option.isNone(latest) || isMoving(latest.value)) { + return null; + } + const thread = latest.value; + const turn = thread.latestTurn; + const lookedSince = + turn !== null && + turn.state === "completed" && + Date.parse(turn.requestedAt) >= Date.parse(pending.requestedAt); + if ( + !fixSwitchOn(thread, number, input.holders) || + hasWorkInProgress(thread) || + !lookedSince + ) { + return null; + } - yield* forget; - const outcome = yield* Effect.exit( - pullRequestService.runAction({ - projectId: input.reference.projectId, - repository: input.reference.repository, - number, - action: "enable-auto-merge", + yield* forget; + const outcome = yield* Effect.exit( + pullRequestService.runAction({ + projectId: input.reference.projectId, + repository: input.reference.repository, + number, + action: "enable-auto-merge", + }), + ); + return { thread, outcome }; }), ); + if (acted === null) { + return; + } + const { thread, outcome } = acted; if (Exit.isSuccess(outcome)) { yield* Effect.logInfo("pull-request.auto-fix.requeued", { threadId: thread.id, number }); yield* appendAutoMergeActivity({ @@ -1240,34 +1275,46 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher // be sent to. What would have been said stays news: the baseline goes // back to the one this look started from, and the first look after // that says it if it still needs saying. - const latest = yield* attempt( - "thread-read", + // A move under way, or waiting, means not here: the news stays news. + const turn = yield* actionGate.withThread( thread.id, - projectionSnapshotQuery.getThreadShellById(thread.id), + Effect.gen(function* () { + const latest = yield* attempt( + "thread-read", + thread.id, + projectionSnapshotQuery.getThreadShellById(thread.id), + ); + if ( + latest === null || + Option.isNone(latest) || + isMoving(latest.value) || + !fixSwitchOn(latest.value, number, watch.holders) || + hasWorkInProgress(latest.value) || + (checkout.kind === "folder" && (yield* folderBusyElsewhere(thread.id, checkout.path))) + ) { + return null; + } + return { + requestedAt: yield* startTurn({ + thread: latest.value, + number, + text, + trigger: [ + newQueueRemoval === null ? null : "merge-queue", + newlyFailing.length === 0 ? null : "checks", + newComments.length === 0 ? null : "comments", + ] + .filter((part) => part !== null) + .join("-and-"), + }), + }; + }), ); - if ( - latest === null || - Option.isNone(latest) || - !fixSwitchOn(latest.value, number, watch.holders) || - hasWorkInProgress(latest.value) || - (checkout.kind === "folder" && (yield* folderBusyElsewhere(thread.id, checkout.path))) - ) { + if (turn === null) { yield* Ref.update(baselinesRef, (map) => map.set(key, baseline)); return "watching"; } - - const requestedAt = yield* startTurn({ - thread: latest.value, - number, - text, - trigger: [ - newQueueRemoval === null ? null : "merge-queue", - newlyFailing.length === 0 ? null : "checks", - newComments.length === 0 ? null : "comments", - ] - .filter((part) => part !== null) - .join("-and-"), - }); + const { requestedAt } = turn; // The baseline advances either way: a dispatch the engine refused is not // one to retry every two minutes. yield* Ref.update(baselinesRef, (map) => diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index 19558455a..64bf65bdc 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -39,6 +39,7 @@ import { ThreadMoveAbortedPayload as ContractsThreadMoveAbortedPayloadSchema, ThreadMovedAwayPayload as ContractsThreadMovedAwayPayloadSchema, ThreadHistorySeedDeliveredPayload as ContractsThreadHistorySeedDeliveredPayloadSchema, + ThreadMoveRestoreSetPayload as ContractsThreadMoveRestoreSetPayloadSchema, ThreadRemoteChildUpdatedPayload as ContractsThreadRemoteChildUpdatedPayloadSchema, ThreadParentAttachmentSetPayload as ContractsThreadParentAttachmentSetPayloadSchema, ThreadSideTurnInterruptRequestedPayload as ContractsThreadSideTurnInterruptRequestedPayloadSchema, @@ -135,6 +136,7 @@ export const ThreadMoveCancelRequestedPayload = ContractsThreadMoveCancelRequest export const ThreadMoveAbortedPayload = ContractsThreadMoveAbortedPayloadSchema; export const ThreadMovedAwayPayload = ContractsThreadMovedAwayPayloadSchema; export const ThreadHistorySeedDeliveredPayload = ContractsThreadHistorySeedDeliveredPayloadSchema; +export const ThreadMoveRestoreSetPayload = ContractsThreadMoveRestoreSetPayloadSchema; export const ThreadParentAttachmentSetPayload = ContractsThreadParentAttachmentSetPayloadSchema; export const ThreadSideTurnInterruptRequestedPayload = ContractsThreadSideTurnInterruptRequestedPayloadSchema; diff --git a/apps/server/src/orchestration/decider.generalChats.test.ts b/apps/server/src/orchestration/decider.generalChats.test.ts index fa786dd8f..7d10bb0c0 100644 --- a/apps/server/src/orchestration/decider.generalChats.test.ts +++ b/apps/server/src/orchestration/decider.generalChats.test.ts @@ -20,6 +20,7 @@ import { describe, expect, it } from "vite-plus/test"; import { decideOrchestrationCommand } from "./decider.ts"; import { resolveThreadProviderCwd } from "./generalChats.ts"; import { createEmptyReadModel, projectEvent } from "./projector.ts"; +import { threadMoveRefusals } from "./threadMoveDecisions.ts"; const now = "2026-01-01T00:00:00.000Z"; const asCommandId = (value: string): CommandId => CommandId.make(value); @@ -566,3 +567,56 @@ describe("resolveThreadProviderCwd", () => { expect(cwd).toBe("/worktrees/project-a/thread-a"); }); }); + +describe("moving a general chat (docs/design/fleet.md, Part 3e)", () => { + async function apply(readModel: OrchestrationReadModel, command: OrchestrationCommand) { + const decided = await Effect.runPromise(decideOrchestrationCommand({ command, readModel })); + let model = readModel; + for (const [index, event] of (Array.isArray(decided) ? decided : [decided]).entries()) { + model = await Effect.runPromise( + projectEvent(model, { ...event, sequence: model.snapshotSequence + index + 1 } as never), + ); + } + return model; + } + const chat = (id: string): OrchestrationCommand => ({ + type: "thread.create", + commandId: asCommandId(`cmd-create-${id}`), + threadId: asThreadId(id), + projectId: asProjectId("project-general-chats"), + title: id, + modelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + }); + + it("works in a folder of its own: another chat at work doesn't hold its move", async () => { + let model = await seedGeneralChatsReadModel(); + model = await apply(model, chat("chat-busy")); + model = await apply(model, chat("chat-moving")); + model = await apply(model, { + type: "thread.session.set", + commandId: asCommandId("cmd-busy-session"), + threadId: asThreadId("chat-busy"), + session: { + threadId: asThreadId("chat-busy"), + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + } as OrchestrationCommand); + const moving = model.threads.find((thread) => thread.id === "chat-moving")!; + expect(threadMoveRefusals(model, moving, { threadState: true, generalChats: true })).toEqual( + [], + ); + // An older computer still can't take one. + expect(threadMoveRefusals(model, moving).map((entry) => entry.code)).toEqual(["general_chat"]); + }); +}); diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index ffdf99dc0..05bcd8272 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -15,7 +15,12 @@ import { type OrchestrationCommand, type OrchestrationEvent, type OrchestrationReadModel, + type OrchestrationQueuedFollowUp, type OrchestrationSession, + type OrchestrationThread, + type OrchestrationThreadGoal, + type ThreadGoalStatus, + type ThreadMoveTakes, type ThreadPendingMoveMode, } from "@threadlines/contracts"; import * as Effect from "effect/Effect"; @@ -824,3 +829,665 @@ describe("a move that waits for the thread to be free", () => { expect(threadMoveGuardRefusal(model, turnStart())).toBeNull(); }); }); + +describe("a move carries what its thread had going (Part 3e)", () => { + const REQUEST = ThreadMoveRequestId.make("request-carry"); + const TAKES_ALL = { threadState: true, generalChats: true } as const; + const queue = ( + options: { + readonly mode?: ThreadPendingMoveMode; + readonly takes?: ThreadMoveTakes; + readonly threadId?: ThreadId; + } = {}, + ): OrchestrationCommand => ({ + type: "thread.move.queue", + commandId: nextCommandId(), + threadId: options.threadId ?? THREAD, + requestId: REQUEST, + target: MAC_MINI, + agent: modelSelection, + mode: options.mode ?? "when-done", + requestedBy: { kind: "user" }, + ...(options.takes !== undefined ? { targetTakes: options.takes } : {}), + createdAt: now, + }); + const withThread = ( + model: OrchestrationReadModel, + patch: Partial, + threadId = THREAD, + ): OrchestrationReadModel => ({ + ...model, + threads: model.threads.map((thread) => + thread.id === threadId ? ({ ...thread, ...patch } as OrchestrationThread) : thread, + ), + }); + const goal = (status: ThreadGoalStatus, extra?: Partial) => ({ + threadId: THREAD, + objective: "Make the suite pass", + status, + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: now, + updatedAt: now, + ...extra, + }); + const checkBack = (id: string, durable = false) => ({ + id, + participantId: null, + scheduledFor: "2026-10-22T10:30:00.000Z", + exact: true, + recurring: false, + description: "Look at CI", + prompt: "Look at CI on #212", + durable, + }); + const queued = (id: string, extra?: Record) => + ({ + messageId: MessageId.make(id), + text: "and then this", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + ...extra, + }) as OrchestrationQueuedFollowUp; + const withSession = ( + model: OrchestrationReadModel, + status: OrchestrationSession["status"], + activeTurnId: TurnId | null = null, + ) => + project(model, "thread.session-set", { + threadId: THREAD, + session: { + threadId: THREAD, + status, + providerName: "codex", + runtimeMode: "auto", + activeTurnId, + lastError: null, + updatedAt: now, + }, + }); + + it("each thing a thread had going is refused for a computer that doesn't take it, and allowed for one that does", async () => { + const base = await seeded(); + const latestTurn = { + turnId: TurnId.make("turn-plan"), + state: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + assistantMessageId: null, + } as OrchestrationThread["latestTurn"]; + const cases: ReadonlyArray = [ + ["a goal", withThread(base, { goal: goal("active") }), "has a goal set"], + ["a check-back", withThread(base, { checkBacks: [checkBack("cb-1")] }), "come back"], + ["pull request auto-fix", withThread(base, { pullRequestAutoFix: true }), "auto-fix"], + ["a queued message", withThread(base, { queuedFollowUps: [queued("q-1")] }), "queued"], + [ + "a plan waiting", + withThread(base, { + latestTurn, + proposedPlans: [ + { + id: "plan-1", + turnId: TurnId.make("turn-plan"), + planMarkdown: "1. Fix it", + implementedAt: null, + implementationThreadId: null, + dismissedAt: null, + createdAt: now, + updatedAt: now, + }, + ], + }), + "plan", + ], + ]; + for (const [what, model, words] of cases) { + expect((await apply(model, queue())).refusal, what).toContain(words); + expect( + (await apply(model, queue({ takes: { threadState: true } }))).refusal, + what, + ).toBeNull(); + } + + // A general chat: no project to match, its own folder. + const GENERAL = ProjectId.make("project-general-chats"); + const CHAT = ThreadId.make("thread-chat"); + let model = base; + ({ model } = await apply(model, { + type: "project.create", + commandId: nextCommandId(), + projectId: GENERAL, + kind: "general-chat", + title: "General Chats", + workspaceRoot: "/state/general-chats", + createdAt: now, + } as OrchestrationCommand)); + ({ model } = await apply(model, { + type: "thread.create", + commandId: nextCommandId(), + threadId: CHAT, + projectId: GENERAL, + title: "Ideas", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: now, + })); + expect((await apply(model, queue({ threadId: CHAT }))).refusal).toContain("General chats"); + expect( + (await apply(model, queue({ threadId: CHAT, takes: { threadState: true } }))).refusal, + ).toContain("General chats"); + expect((await apply(model, queue({ threadId: CHAT, takes: TAKES_ALL }))).refusal).toBeNull(); + }); + + it("a message queued by a scheduled task, another thread or an assistant still keeps the thread here", async () => { + const model = withThread(await seeded(), { + queuedFollowUps: [queued("q-scheduled", { scheduledTaskId: "task-1" })], + }); + expect((await apply(model, queue({ takes: TAKES_ALL }))).refusal).toContain( + "A scheduled task's message is waiting its turn. Move once it has been sent, or remove it.", + ); + }); + + it("a check-back Claude saved to disk is named as such for a computer that can't take it", async () => { + const model = withThread(await seeded(), { checkBacks: [checkBack("cb-saved", true)] }); + expect((await apply(model, queue())).refusal).toContain( + "Claude saved this thread's check-back to disk. Ask the agent to delete it, then move.", + ); + }); + + it("each decision that plans the stop records what it takes, and only ever adds to it", async () => { + const working = withThread( + await withSession(await seeded(), "running", TurnId.make("turn-1")), + { goal: goal("active"), checkBacks: [checkBack("cb-1")] }, + ); + // Stop and move now: at once. + const stopNow = await apply(working, queue({ mode: "stop-now", takes: TAKES_ALL })); + expect(threadOf(stopNow.model).pendingMove?.interrupted).toEqual({ + goalActive: true, + checkBacks: [checkBack("cb-1")], + }); + + // Move when it's done: nothing yet, then the barrier's quiesce once it's free. + const free = withThread(await withSession(await seeded(), "ready"), { + goal: goal("active"), + checkBacks: [checkBack("cb-1")], + }); + let model = (await apply(free, queue({ takes: TAKES_ALL }))).model; + expect(threadOf(model).pendingMove?.interrupted).toBeUndefined(); + ({ model } = await apply(model, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + createdAt: now, + })); + expect(threadOf(model).pendingMove?.interrupted).toMatchObject({ goalActive: true }); + // The stop paused the goal and ended the check-back; a turn slipped in + // and set another: asked to stop again, the record keeps both and the goal. + model = withThread(await withSession(model, "ready"), { + goal: goal("paused"), + checkBacks: [checkBack("cb-2")], + }); + ({ model } = await apply(model, { + type: "thread.move.quiesce", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + createdAt: now, + })); + expect(threadOf(model).pendingMove?.interrupted).toEqual({ + goalActive: true, + checkBacks: [checkBack("cb-1"), checkBack("cb-2")], + }); + + // The freeze carries it to the move, with what the target said it takes. + model = withThread(await withSession(model, "stopped"), { checkBacks: [] }); + ({ model } = await apply(model, { + type: "thread.move.start", + commandId: nextCommandId(), + threadId: THREAD, + transferId: TRANSFER, + target: MAC_MINI, + agent: modelSelection, + queuedRequestId: REQUEST, + targetTakes: TAKES_ALL, + createdAt: now, + })); + expect(threadOf(model).move).toMatchObject({ + interrupted: { goalActive: true }, + targetTakes: TAKES_ALL, + }); + + // "Stop the agents and move now" on a waiting move records it too. + const waiting = (await apply(free, queue({ takes: TAKES_ALL }))).model; + const switched = await apply(waiting, { + type: "thread.move.set-mode", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + mode: "stop-now", + createdAt: now, + }); + expect(threadOf(switched.model).pendingMove?.interrupted).toMatchObject({ goalActive: true }); + + // A direct move whose session still runs records it in the freeze. + const ready = withThread(await withSession(await seeded(), "ready"), { + goal: goal("active"), + }); + const direct = await apply(ready, { + ...startMove(), + targetTakes: TAKES_ALL, + } as OrchestrationCommand); + expect(direct.refusal).toBeNull(); + expect(threadOf(direct.model).move?.interrupted).toEqual({ goalActive: true }); + }); + + it("a frozen thread still takes what its provider reports of its goal", async () => { + const frozen = ( + await apply(withThread(await seeded(), { goal: goal("active") }), { + ...startMove(), + targetTakes: TAKES_ALL, + } as OrchestrationCommand) + ).model; + const reported = await apply(frozen, { + type: "thread.goal.state.set", + commandId: nextCommandId(), + threadId: THREAD, + goal: goal("paused"), + createdAt: now, + }); + expect(reported.refusal).toBeNull(); + expect(threadOf(reported.model).goal?.status).toBe("paused"); + }); + + it("no queued message is sent while a move waits; what goes into a running turn still does", async () => { + const model = withThread((await apply(await seeded(), queue({ takes: TAKES_ALL }))).model, { + queuedFollowUps: [queued("q-1")], + }); + const send = { + type: "thread.follow-up.send-queued", + commandId: nextCommandId(), + threadId: THREAD, + messageId: MessageId.make("q-1"), + createdAt: now, + } as OrchestrationCommand; + expect(threadMoveGuardRefusal(model, send)).toContain("waiting to move"); + expect( + threadMoveGuardRefusal(model, { ...send, steeredTurnId: TurnId.make("turn-1") } as never), + ).toBeNull(); + }); + + it("the read-only copy keeps no queue and no switch on", async () => { + let model = withThread(await seeded(), { + queuedFollowUps: [queued("q-1")], + pullRequestAutoFix: true, + linkedPullRequests: [ + { + number: 212, + url: "https://github.com/acme/w/pull/212", + autoFix: false, + autoMerge: "squash", + }, + ], + }); + ({ model } = await apply(model, { + ...startMove(), + targetTakes: TAKES_ALL, + } as OrchestrationCommand)); + ({ model } = await apply(model, { + type: "thread.move.complete", + commandId: nextCommandId(), + threadId: THREAD, + transferId: TRANSFER, + movedThreadId: ThreadId.make("thread-there"), + createdAt: now, + })); + const copy = threadOf(model); + expect(copy.queuedFollowUps ?? []).toEqual([]); + expect(copy.pullRequestAutoFix).toBe(false); + expect(copy.linkedPullRequests).toMatchObject([ + { number: 212, autoFix: false, autoMerge: null }, + ]); + }); + + it("a move that doesn't happen owes back what its stop took, until it is paid", async () => { + const working = withThread( + await withSession(await seeded(), "running", TurnId.make("turn-1")), + { goal: goal("active"), checkBacks: [checkBack("cb-1")], queuedFollowUps: [queued("q-1")] }, + ); + let model = (await apply(working, queue({ mode: "stop-now", takes: TAKES_ALL }))).model; + // The stop paused the goal (Codex) and ended the check-back. + model = withThread(await withSession(model, "stopped"), { + goal: goal("paused"), + checkBacks: [], + }); + ({ model } = await apply(model, { + type: "thread.move.unqueue", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + createdAt: now, + })); + const owed = threadOf(model).moveRestoreOwed; + expect(owed).toMatchObject({ + target: MAC_MINI, + interrupted: { goalActive: true, checkBacks: [checkBack("cb-1")] }, + queued: true, + }); + + // Paid in one decision: the goal is on again, the agent's message goes + // ahead of the user's queue, and only the goal's hand-over is left. + ({ model } = await apply(model, { + type: "thread.move.restore", + commandId: nextCommandId(), + threadId: THREAD, + at: owed!.at, + message: { + messageId: MessageId.make("m-put-back"), + text: "The move to Mac mini didn't happen.", + }, + createdAt: now, + })); + const paid = threadOf(model); + expect(paid.goal?.status).toBe("active"); + expect(paid.queuedFollowUps?.map((entry) => entry.messageId)).toEqual(["m-put-back", "q-1"]); + expect(paid.queuedFollowUps?.[0]?.afterMove).toBe(true); + expect(paid.moveRestoreOwed).toMatchObject({ goalOwed: true }); + // The same pay again is no news; the goal's hand-over clears it. + const again = await Effect.runPromise( + decideOrchestrationCommand({ + readModel: model, + command: { + type: "thread.move.restore", + commandId: nextCommandId(), + threadId: THREAD, + at: owed!.at, + createdAt: now, + }, + }), + ); + expect(Array.isArray(again) ? again : [again]).toEqual([]); + ({ model } = await apply(model, { + type: "thread.move.restore", + commandId: nextCommandId(), + threadId: THREAD, + at: owed!.at, + finished: true, + createdAt: now, + })); + expect(threadOf(model).moveRestoreOwed ?? null).toBeNull(); + }); + + it("a goal that finished stays finished, and an archived thread is owed nothing", async () => { + const stopped = ( + await apply( + withThread(await withSession(await seeded(), "running", TurnId.make("turn-1")), { + goal: goal("active"), + }), + queue({ mode: "stop-now", takes: TAKES_ALL }), + ) + ).model; + // The goal was met as its agent stopped. + let model = withThread(await withSession(stopped, "stopped"), { goal: goal("complete") }); + ({ model } = await apply(model, { + type: "thread.move.queue-end", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + reason: "blocked", + words: "Update Threadlines on Mac mini to move this thread: it has a goal.", + createdAt: now, + })); + const owed = threadOf(model).moveRestoreOwed!; + ({ model } = await apply(model, { + type: "thread.move.restore", + commandId: nextCommandId(), + threadId: THREAD, + at: owed.at, + createdAt: now, + })); + expect(threadOf(model).goal?.status).toBe("complete"); + expect(threadOf(model).moveRestoreOwed ?? null).toBeNull(); + + const gone = await apply(stopped, { + type: "thread.move.queue-end", + commandId: nextCommandId(), + threadId: THREAD, + requestId: REQUEST, + reason: "gone", + words: "This thread was archived.", + createdAt: now, + }); + expect(threadOf(gone.model).moveRestoreOwed ?? null).toBeNull(); + }); + + it("a dropped move owes back what its stop took", async () => { + let model = withThread(await withSession(await seeded(), "ready"), { + goal: goal("active"), + }); + ({ model } = await apply(model, { + ...startMove(), + targetTakes: TAKES_ALL, + } as OrchestrationCommand)); + ({ model } = await apply(model, { + type: "thread.move.abort", + commandId: nextCommandId(), + threadId: THREAD, + transferId: TRANSFER, + reason: "Mac mini didn't allow the move.", + code: "denied", + createdAt: now, + })); + expect(threadOf(model).moveRestoreOwed).toMatchObject({ interrupted: { goalActive: true } }); + }); + + it("an import writes the goal, pull requests, plans and queue with the thread, the arrival first", async () => { + const model = await seeded(); + const ARRIVED = ThreadId.make("thread-arrived"); + const events = await Effect.runPromise( + decideOrchestrationCommand({ + readModel: model, + command: { + type: "thread.import", + commandId: nextCommandId(), + threadId: ARRIVED, + projectId: PROJECT, + title: "Fix the flaky test", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/flaky", + worktreePath: "/worktrees/moved-1", + movedFrom: { ...MAC_MINI, threadId: THREAD, movedAt: now }, + messages: [], + activities: [], + goal: { ...goal("active"), threadId: ARRIVED }, + pullRequests: { + autoFix: true, + autoMerge: null, + linked: [ + { + number: 212, + url: "https://github.com/acme/w/pull/212", + autoFix: true, + autoMerge: null, + }, + ], + }, + queuedFollowUps: [queued("q-there")], + proposedPlans: [ + { + id: "plan-there", + turnId: null, + planMarkdown: "1. Fix it", + implementedAt: null, + implementationThreadId: null, + dismissedAt: null, + createdAt: now, + updatedAt: now, + }, + ], + arrival: { + message: { messageId: MessageId.make("m-arrival"), text: "This thread moved." }, + brought: ["its goal", "1 queued message", "auto-fix for #212"], + left: [], + }, + createdAt: now, + }, + }), + ); + const planned = Array.isArray(events) ? events : [events]; + expect(planned.map((event) => event.type)).toEqual([ + "thread.created", + "thread.goal-state-set", + "thread.pull-request-linked", + "thread.pull-request-automation-changed", + "thread.pull-request-automation-changed", + "thread.proposed-plan-upserted", + "thread.follow-up-queued", + "thread.follow-up-queued", + "thread.activity-appended", + ]); + const queuedEvents = planned.filter((event) => event.type === "thread.follow-up-queued"); + expect(queuedEvents.map((event) => event.payload)).toMatchObject([ + { imported: true, followUp: { messageId: "m-arrival", afterMove: true } }, + { imported: true, followUp: { messageId: "q-there" } }, + ]); + expect(planned.at(-1)?.payload).toMatchObject({ + activity: { + kind: "thread.moved-in", + payload: { brought: ["its goal", "1 queued message", "auto-fix for #212"] }, + }, + }); + }); + + it("resume on a moved thread whose agent wasn't given the conversation waits for the message that gives it", async () => { + const ARRIVED = ThreadId.make("thread-resumed"); + const arrived = ( + await apply(await seeded(), { + type: "thread.import", + commandId: nextCommandId(), + threadId: ARRIVED, + projectId: PROJECT, + title: "Fix the flaky test", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/flaky", + worktreePath: "/worktrees/moved-2", + movedFrom: { ...MAC_MINI, threadId: THREAD, movedAt: now }, + messages: [], + activities: [], + goal: { ...goal("paused"), threadId: ARRIVED }, + createdAt: now, + }) + ).model; + const resumed = await Effect.runPromise( + decideOrchestrationCommand({ + readModel: arrived, + command: { + type: "thread.goal.set", + commandId: nextCommandId(), + threadId: ARRIVED, + status: "active", + createdAt: now, + }, + }), + ); + const planned = Array.isArray(resumed) ? resumed : [resumed]; + // No provider call: the goal reads on, and a message for its agent waits. + expect(planned.map((event) => event.type)).toEqual([ + "thread.goal-state-set", + "thread.follow-up-queued", + ]); + }); +}); + +describe("a moved thread that moves on, or edits its goal before its agent knows it (Part 3e)", () => { + const ARRIVED = ThreadId.make("thread-arrived-twice"); + const importHere = (extra: Record): OrchestrationCommand => + ({ + type: "thread.import", + commandId: nextCommandId(), + threadId: ARRIVED, + projectId: PROJECT, + title: "Fix the flaky test", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: "fix/flaky", + worktreePath: "/worktrees/moved-3", + movedFrom: { ...MAC_MINI, threadId: THREAD, movedAt: now }, + messages: [], + activities: [], + createdAt: now, + ...extra, + }) as OrchestrationCommand; + + it("a plan that arrived waiting still keeps the thread from a computer that can't take it", async () => { + const arrived = ( + await apply( + await seeded(), + importHere({ + proposedPlans: [ + { + id: "plan-there", + turnId: null, + planMarkdown: "1. Fix it", + implementedAt: null, + implementationThreadId: null, + dismissedAt: null, + createdAt: now, + updatedAt: now, + }, + ], + }), + ) + ).model; + const queueOn = (takes?: ThreadMoveTakes): OrchestrationCommand => ({ + type: "thread.move.queue", + commandId: nextCommandId(), + threadId: ARRIVED, + requestId: ThreadMoveRequestId.make("request-again"), + target: { environmentId: EnvironmentId.make("environment-pc"), label: "Windows PC" }, + agent: modelSelection, + mode: "when-done", + requestedBy: { kind: "user" }, + ...(takes !== undefined ? { targetTakes: takes } : {}), + createdAt: now, + }); + expect((await apply(arrived, queueOn())).refusal).toContain("plan"); + expect((await apply(arrived, queueOn({ threadState: true }))).refusal).toBeNull(); + }); + + it("a goal set before its agent was given the conversation waits for the message that gives it", async () => { + const arrived = (await apply(await seeded(), importHere({}))).model; + const decided = await Effect.runPromise( + decideOrchestrationCommand({ + readModel: arrived, + command: { + type: "thread.goal.set", + commandId: nextCommandId(), + threadId: ARRIVED, + objective: "Ship the fix", + createdAt: now, + }, + }), + ); + const planned = Array.isArray(decided) ? decided : [decided]; + expect(planned.map((event) => event.type)).toEqual([ + "thread.goal-state-set", + "thread.follow-up-queued", + ]); + expect(planned[0]?.payload).toMatchObject({ + goal: { objective: "Ship the fix", status: "active" }, + }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 4aaee8332..a942e9b99 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -129,6 +129,8 @@ import { decideMoveSetMode, decideMoveStart, decideMoveUnqueue, + decideMovedGoalResume, + decideMoveRestore, decideThreadImport, threadMoveGuardRefusal, } from "./threadMoveDecisions.ts"; @@ -2463,6 +2465,34 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ); } + // Put back what a move that didn't happen took (Part 3e). + case "thread.move.restore": { + const thread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const restored = yield* planChildThreadDecision( + command.type, + decideMoveRestore(thread, command, childEventBase(command, command.createdAt)), + ); + if (restored.length === 0 || command.sendQueued === undefined) return restored; + // The queue that waited for the move, sent in the same decision. + const sent = yield* decideCommandSequence({ + readModel, + commands: [ + { + type: "thread.follow-up.send-queued", + commandId: command.commandId, + threadId: command.threadId, + messageId: command.sendQueued, + createdAt: command.createdAt, + }, + ], + }); + return [...restored, ...sent]; + } + case "thread.move.start": case "thread.move.progress": case "thread.move.cancel": @@ -3855,14 +3885,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ], }); if (!agentQueued) { - // It counted as the user writing when it was queued. + // It counted as the user writing when it was queued. One Threadlines + // wrote for a move is written as such (OrchestrationMessage.afterMove). return [ unqueuedEvent, - ...turnEvents.filter( - (event) => - event.type !== "thread.agent-requests-reset" && - event.type !== "thread.child-requests-reset", - ), + ...turnEvents + .filter( + (event) => + event.type !== "thread.agent-requests-reset" && + event.type !== "thread.child-requests-reset", + ) + .map((event): PlannedOrchestrationEvent => + queued.afterMove === true && + event.type === "thread.message-sent" && + (event.payload as { readonly messageId?: unknown }).messageId === queued.messageId + ? ({ + ...event, + payload: { + ...(event.payload as Extract< + OrchestrationEvent, + { type: "thread.message-sent" } + >["payload"]), + afterMove: true, + }, + } as PlannedOrchestrationEvent) + : event, + ), ]; } // The agent's message was written when it was queued; sending it keeps @@ -4708,11 +4756,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" case "thread.goal.set": { yield* refuseSkippedSetup(command); - yield* requireThread({ + const goalThread = yield* requireThread({ readModel, command, threadId: command.threadId, }); + // Resume on a moved thread whose agent hasn't been given the + // conversation yet: no provider call, the goal waits for the message + // that gives it (docs/design/fleet.md, Part 3e, (a)). + const movedResume = decideMovedGoalResume( + goalThread, + command, + childEventBase(command, command.createdAt), + ); + if (movedResume !== null) { + return yield* planChildThreadDecision(command.type, movedResume); + } return { ...withEventBase({ aggregateKind: "thread", diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index e17319969..b9cb1ccfd 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -37,6 +37,7 @@ import { } from "@threadlines/shared/roomAgentRequests"; import { applyAgentPagePublication } from "@threadlines/shared/agentPages"; import { nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; +import { withQueuedFollowUp } from "@threadlines/shared/queuedFollowUps"; import { applyCommandRequestDismissed, applyCommandRequested, @@ -112,6 +113,7 @@ import { ThreadRemoteCancelsDeliveredPayload, ThreadRemoteChildUpdatedPayload, ThreadHistorySeedDeliveredPayload, + ThreadMoveRestoreSetPayload, ThreadParentAttachmentSetPayload, ThreadSideTurnInterruptRequestedPayload, ThreadSideTurnRunningPayload, @@ -1064,6 +1066,17 @@ export function projectEvent( }); } + // What a move that didn't happen owes the thread back, or that it's paid. + case "thread.move-restore-set": + return decodeForEvent(ThreadMoveRestoreSetPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + moveRestoreOwed: payload.moveRestoreOwed, + }), + })), + ); + case "thread.history-seed-delivered": return decodeForEvent( ThreadHistorySeedDeliveredPayload, @@ -1349,6 +1362,7 @@ export function projectEvent( ...(payload.composer !== undefined ? { composer: payload.composer } : {}), ...(payload.sentFrom !== undefined ? { sentFrom: payload.sentFrom } : {}), ...(payload.trigger !== undefined ? { trigger: payload.trigger } : {}), + ...(payload.afterMove === true ? { afterMove: true as const } : {}), turnId: payload.turnId, streaming: payload.streaming, createdAt: payload.createdAt, @@ -1388,6 +1402,9 @@ export function projectEvent( ? { trigger: message.trigger } : {}), ...(entry.notSent === true ? { notSent: true as const } : {}), + ...(entry.afterMove === true || message.afterMove === true + ? { afterMove: true as const } + : {}), } : entry, ) @@ -1490,12 +1507,7 @@ export function projectEvent( return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { - queuedFollowUps: [ - ...(thread.queuedFollowUps ?? []).filter( - (queued) => queued.messageId !== payload.followUp.messageId, - ), - payload.followUp, - ], + queuedFollowUps: withQueuedFollowUp(thread.queuedFollowUps ?? [], payload.followUp), updatedAt: payload.followUp.createdAt, }), }; diff --git a/apps/server/src/orchestration/threadMoveCarry.ts b/apps/server/src/orchestration/threadMoveCarry.ts new file mode 100644 index 000000000..a9d4361e3 --- /dev/null +++ b/apps/server/src/orchestration/threadMoveCarry.ts @@ -0,0 +1,267 @@ +/** + * What a thread carries when it moves (docs/design/fleet.md, Part 3e, + * "Shared pieces"): its goal, check-backs, pull request switches, General + * Chats folder, queued messages and plans, and which of the other computer's + * capabilities each needs. One pure description for the three that must + * agree: the move checks (`threadMoveRefusals`: refused or not), the dialog's + * lines (the preview), and the export (what to pack). + * + * What the move's stop already took (ThreadMoveInterrupted: a goal that was + * working, check-backs that ended with the session) counts as the thread's, + * so a move that stopped its agent still carries them. + */ +import type { + OrchestrationCheckBack, + OrchestrationProposedPlan, + OrchestrationQueuedFollowUp, + OrchestrationThread, + OrchestrationThreadGoal, + OrchestrationThreadLinkedPullRequest, + PullRequestMergeMethod, + ThreadMoveInterrupted, + ThreadMoveTakes, +} from "@threadlines/contracts"; +import { PEER_MOVE_STATE_MAX_PLANS } from "@threadlines/contracts"; +import { linkedPullRequestArmed } from "@threadlines/shared/linkedPullRequests"; + +/** What a move view needs of a project to tell a General Chats thread. */ +export interface ThreadMoveCarryView { + readonly projects: ReadonlyArray<{ + readonly id: OrchestrationThread["projectId"]; + readonly kind?: string | undefined; + }>; +} + +export interface ThreadMoveCarry { + /** (a) The thread's goal, in any status; null: none. */ + readonly goal: OrchestrationThreadGoal | null; + /** (a) It was working when (or before) the move stopped its agent. */ + readonly goalWorking: boolean; + /** (b) Its agents' check-backs, with the ones the move's stop ended. */ + readonly checkBacks: ReadonlyArray; + /** (c) Its pull request switches, when any is on; null: none on. */ + readonly pullRequests: { + readonly autoFix: boolean; + readonly autoMerge: PullRequestMergeMethod | null; + readonly linked: ReadonlyArray; + } | null; + /** (d) A General Chats thread: its folder moves, not a checkout. */ + readonly generalChat: boolean; + /** (e) The user's own queued messages, in order. */ + readonly queuedFollowUps: ReadonlyArray; + /** (e) Messages queued by something on this computer, which keep blocking. */ + readonly foreignQueued: ReadonlyArray; + /** (f) The plans that come along: the newest PEER_MOVE_STATE_MAX_PLANS, oldest first. */ + readonly proposedPlans: ReadonlyArray; + /** (f) Older plans past the limit, which stay here. */ + readonly plansLeftBehind: number; + /** (f) A plan waits for the user's Implement or Dismiss. */ + readonly planWaiting: boolean; + /** What the other computer must take for this thread to move there. */ + readonly needs: { readonly threadState: boolean; readonly generalChats: boolean }; +} + +/** Everything a current computer takes: the preview's "as if it took everything". */ +export const ALL_MOVE_TAKES: ThreadMoveTakes = { threadState: true, generalChats: true }; + +/** A queued message the user wrote: none of an agent's, a thread's, an outside assistant's or a scheduled run's. */ +export const isUsersQueuedFollowUp = (entry: OrchestrationQueuedFollowUp) => + entry.fromAgent === undefined && + entry.fromThread === undefined && + entry.fromOutside === undefined && + entry.scheduledTaskId === undefined; + +/** + * The plan Implement and Dismiss act on: the newest one on the latest turn, + * unanswered. A thread with no turn yet (one that moved here and hasn't + * worked since) offers its newest plan, as the app does. + */ +export function waitingPlanOf( + thread: Pick, +): OrchestrationProposedPlan | null { + const unanswered = (plan: OrchestrationProposedPlan) => + plan.implementedAt === null && plan.dismissedAt === null; + const latestTurnId = thread.latestTurn?.turnId ?? null; + if (latestTurnId === null) { + const newest = thread.proposedPlans.at(-1); + return newest !== undefined && unanswered(newest) ? newest : null; + } + return ( + thread.proposedPlans.findLast((plan) => plan.turnId === latestTurnId && unanswered(plan)) ?? + null + ); +} + +/** What a move's stop took, merged with what the thread holds now (it is only ever added to). */ +export function mergeInterrupted( + thread: Pick, + earlier: ThreadMoveInterrupted | null | undefined, +): ThreadMoveInterrupted | undefined { + const goalActive = earlier?.goalActive === true || thread.goal?.status === "active"; + const byId = new Map(); + for (const checkBack of earlier?.checkBacks ?? []) byId.set(checkBack.id, checkBack); + for (const checkBack of thread.checkBacks ?? []) byId.set(checkBack.id, checkBack); + const checkBacks = [...byId.values()].toSorted((left, right) => + left.scheduledFor.localeCompare(right.scheduledFor), + ); + if (!goalActive && checkBacks.length === 0) return undefined; + return { + ...(goalActive ? { goalActive: true as const } : {}), + ...(checkBacks.length > 0 ? { checkBacks } : {}), + }; +} + +/** Whether two records of what a stop took say the same. */ +export function sameInterrupted( + left: ThreadMoveInterrupted | null | undefined, + right: ThreadMoveInterrupted | null | undefined, +): boolean { + const ids = (value: ThreadMoveInterrupted | null | undefined) => + (value?.checkBacks ?? []).map((checkBack) => checkBack.id).join("\0"); + return (left?.goalActive === true) === (right?.goalActive === true) && ids(left) === ids(right); +} + +/** What the thread's move under way or waiting recorded its stop took. */ +export const interruptedOf = ( + thread: Pick, +): ThreadMoveInterrupted | undefined => + thread.move?.interrupted ?? thread.pendingMove?.interrupted ?? undefined; + +/** What `thread` carries if it moves now (docs/design/fleet.md, Part 3e). */ +export function threadMoveCarry( + view: ThreadMoveCarryView, + thread: OrchestrationThread, +): ThreadMoveCarry { + const interrupted = mergeInterrupted(thread, interruptedOf(thread)); + const goal = thread.goal ?? null; + const checkBacks = interrupted?.checkBacks ?? []; + const linkedArmed = (thread.linkedPullRequests ?? []).filter(linkedPullRequestArmed); + const ownArmed = thread.pullRequestAutoFix || thread.pullRequestAutoMerge !== null; + const pullRequests = + ownArmed || linkedArmed.length > 0 + ? { + autoFix: thread.pullRequestAutoFix, + autoMerge: thread.pullRequestAutoMerge, + linked: linkedArmed, + } + : null; + const generalChat = + view.projects.find((project) => project.id === thread.projectId)?.kind === "general-chat"; + const queued = thread.queuedFollowUps ?? []; + const queuedFollowUps = queued.filter(isUsersQueuedFollowUp); + const foreignQueued = queued.filter((entry) => !isUsersQueuedFollowUp(entry)); + const proposedPlans = thread.proposedPlans.slice(-PEER_MOVE_STATE_MAX_PLANS); + const planWaiting = waitingPlanOf(thread) !== null; + return { + goal, + goalWorking: interrupted?.goalActive === true, + checkBacks, + pullRequests, + generalChat, + queuedFollowUps, + foreignQueued, + proposedPlans, + plansLeftBehind: thread.proposedPlans.length - proposedPlans.length, + planWaiting, + needs: { + threadState: + (goal !== null && goal.status !== "complete") || + checkBacks.length > 0 || + pullRequests !== null || + queuedFollowUps.length > 0 || + planWaiting, + generalChats: generalChat, + }, + }; +} + +/** + * The first thing the thread carries that `takes` doesn't cover, as the end + * of "Update Threadlines on to move this thread: …", or null when + * it covers everything. + */ +export function carryNotTaken( + carry: ThreadMoveCarry, + takes: ThreadMoveTakes | null | undefined, +): string | null { + if (carry.needs.generalChats && takes?.generalChats !== true) return "it's a general chat"; + if (!carry.needs.threadState || takes?.threadState === true) return null; + if (carry.goal !== null && carry.goal.status !== "complete") return "it has a goal"; + if (carry.checkBacks.length > 0) return "its agent set itself a time to come back"; + if (carry.pullRequests !== null) return "it has pull request auto-fix or auto-merge on"; + if (carry.queuedFollowUps.length > 0) return "it has queued messages"; + return "it has a plan waiting"; +} + +const plural = (count: number, one: string, many: string) => + count === 1 ? `1 ${one}` : `${count} ${many}`; + +/** Which switches watch, in words: "Auto-fix", "Auto-merge", or both. */ +function switchesWords( + fix: boolean, + merge: boolean, +): { readonly words: string; readonly verb: string } { + if (fix && merge) return { words: "Auto-fix and auto-merge", verb: "keep" }; + return { words: fix ? "Auto-fix" : "Auto-merge", verb: "keeps" }; +} + +/** + * What the pull request switches watch, in words ("pull request #212", or + * "this thread's pull request"), and which switches are on. + */ +export function pullRequestCarryWords(pullRequests: NonNullable) { + const fix = pullRequests.autoFix || pullRequests.linked.some((entry) => entry.autoFix); + const merge = + pullRequests.autoMerge !== null || + pullRequests.linked.some((entry) => entry.autoMerge !== null); + const numbers = pullRequests.linked.map((entry) => `#${entry.number}`); + const own = pullRequests.autoFix || pullRequests.autoMerge !== null; + const what = + numbers.length === 0 + ? "this thread's pull request" + : numbers.length === 1 && !own + ? `pull request ${numbers[0]}` + : `pull requests ${[...(own ? ["its own"] : []), ...numbers].join(", ")}`; + return { ...switchesWords(fix, merge), what }; +} + +/** + * The move dialog's lines for what comes along (ThreadMovePreview.brings), + * one per thing, in the server's words. + */ +export function carryBringsWords(carry: ThreadMoveCarry): ReadonlyArray { + const lines: string[] = []; + const goal = carry.goal; + if (goal !== null && goal.status !== "complete") { + lines.push( + goal.status === "active" || carry.goalWorking + ? "Its goal carries on there." + : "Its goal arrives paused.", + ); + } + if (carry.checkBacks.length > 0) { + lines.push( + carry.checkBacks.length === 1 + ? "Its agent sets its check-back again there." + : `Its agent sets its ${carry.checkBacks.length} check-backs again there.`, + ); + } + if (carry.pullRequests !== null) { + const { words, verb, what } = pullRequestCarryWords(carry.pullRequests); + lines.push(`${words} ${verb} watching ${what} from there.`); + } + if (carry.queuedFollowUps.length > 0) { + lines.push( + carry.queuedFollowUps.length === 1 + ? "1 queued message is sent there." + : `${carry.queuedFollowUps.length} queued messages are sent there.`, + ); + } + if (carry.planWaiting) lines.push("The plan waits for you there."); + if (carry.plansLeftBehind > 0) { + lines.push( + `${plural(carry.plansLeftBehind, "older plan stays", "older plans stay")} on this computer.`, + ); + } + return lines; +} diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 07ead7aae..126f03bdc 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -14,12 +14,19 @@ import { LEAD_MOVE_REFUSAL } from "@threadlines/shared/projectLead"; import { EventId, + MessageId, type OrchestrationCommand, type OrchestrationEvent, type OrchestrationReadModel, + type OrchestrationQueuedFollowUp, type OrchestrationThread, + type OrchestrationThreadMove, type ThreadId, type ThreadMoveHold, + type ThreadMoveInterrupted, + type ThreadMoveRestore, + type ThreadMoveTakes, + type ThreadMoveTarget, ThreadMoveNotStartedActivityKind, type ThreadMoveNotStartedPayload, type ThreadMoveWait, @@ -36,7 +43,15 @@ import { } from "@threadlines/shared/pendingRequests"; import { isRoomThread } from "@threadlines/shared/threadParticipants"; +import { arrivalMessageText, resumedGoalMessageText } from "../moves/arrivalMessage.ts"; +import { derivedUuid } from "./childRequestIds.ts"; import { childHasLiveWork } from "./childThreadDecisions.ts"; +import { + interruptedOf, + mergeInterrupted, + sameInterrupted, + threadMoveCarry, +} from "./threadMoveCarry.ts"; import { SETTINGS_CHANGE_CANCELLED, cancelWaitingSettingsChanges, @@ -122,13 +137,31 @@ export interface ThreadMoveView { readonly threads: ReadonlyArray; } -/** A thread's checkout: its worktree, else its project's folder. */ +/** + * A thread's checkout, as a key two threads share when they work in the same + * files: its worktree, else its project's folder. A general chat works in a + * folder of its own (generalChatThreadScratchCwd), so no two of them share one. + */ function checkoutOf(readModel: ThreadMoveView, thread: OrchestrationThread) { - return ( - thread.worktreePath ?? - readModel.projects.find((entry) => entry.id === thread.projectId)?.workspaceRoot ?? - null - ); + if (thread.worktreePath !== null) return thread.worktreePath; + const project = readModel.projects.find((entry) => entry.id === thread.projectId); + if (project === undefined) return null; + return project.kind === "general-chat" + ? `${project.workspaceRoot}\u0000${thread.id}` + : project.workspaceRoot; +} + +/** Whose queued message keeps a thread here, in words. */ +function foreignQueuedWords(entry: OrchestrationQueuedFollowUp): string { + const whose = + entry.scheduledTaskId !== undefined + ? "A scheduled task's message" + : entry.fromOutside !== undefined + ? "An outside assistant's message" + : entry.fromThread !== undefined + ? "A message from another thread" + : "An agent's message"; + return `${whose} is waiting its turn. Move once it has been sent, or remove it.`; } /** @@ -142,8 +175,13 @@ function checkoutOf(readModel: ThreadMoveView, thread: OrchestrationThread) { export function threadMoveRefusals( readModel: ThreadMoveView, thread: OrchestrationThread, + takes?: ThreadMoveTakes | null, ): ReadonlyArray { const found: ThreadMoveRefusalEntry[] = []; + // What rides along (docs/design/fleet.md, Part 3e) is refused only when the + // other computer doesn't take it. Absent `takes`: nothing beyond v1. + const carry = threadMoveCarry(readModel, thread); + const takesState = takes?.threadState === true; if (thread.deletedAt !== null) found.push(blocked("deleted", "This thread was deleted.")); if (thread.archivedAt !== null) { found.push(blocked("archived", "Archived threads can't move. Unarchive it first.")); @@ -157,7 +195,7 @@ export function threadMoveRefusals( ); } const project = readModel.projects.find((candidate) => candidate.id === thread.projectId); - if (project?.kind === "general-chat") { + if (project?.kind === "general-chat" && takes?.generalChats !== true) { found.push(blocked("general_chat", "General chats can't move yet.")); } // Words only: the move's refusal code is a closed set older peers decode. @@ -193,29 +231,32 @@ export function threadMoveRefusals( ) { found.push(blocked("has_children", "Threads that started other threads can't move yet.")); } - // Queued follow-ups would start the next turn the moment this one ends. - if ((thread.queuedFollowUps ?? []).length > 0) { + // A message queued by something on this computer answers to it (a + // scheduled run, an outside assistant, another thread), so it is sent + // here. The user's own travel when the other computer takes them. + const foreign = carry.foreignQueued[0]; + if (foreign !== undefined) { + found.push(blocked("queued_messages", foreignQueuedWords(foreign))); + } else if (carry.queuedFollowUps.length > 0 && !takesState) { + // They would start the next turn the moment this one ends. found.push(blocked("queued_messages", "Send or remove your queued messages first.")); } // Only the user's answer clears a plan, and implementing it starts a turn. - const latestTurnId = thread.latestTurn?.turnId ?? null; - if ( - thread.proposedPlans.some( - (plan) => - latestTurnId !== null && - plan.turnId === latestTurnId && - plan.implementedAt === null && - plan.dismissedAt === null, - ) - ) { + if (carry.planWaiting && !takesState) { found.push(blocked("plan", "Implement or dismiss the plan first.")); } - if (thread.goal !== null && thread.goal.status !== "complete") { + if (carry.goal !== null && carry.goal.status !== "complete" && !takesState) { found.push(blocked("goal", "This thread has a goal set. Clear it first.")); } - if ((thread.checkBacks ?? []).length > 0) { + if (carry.checkBacks.length > 0 && !takesState) { + // A saved one can't be cancelled here: stopping the runtime doesn't remove it. found.push( - blocked("check_back", "This thread's agent set itself a time to come back. Cancel it first."), + blocked( + "check_back", + carry.checkBacks.every((checkBack) => checkBack.durable) + ? "Claude saved this thread's check-back to disk. Ask the agent to delete it, then move." + : "This thread's agent set itself a time to come back. Cancel it first.", + ), ); } const runRequestIds = new Set( @@ -235,7 +276,7 @@ export function threadMoveRefusals( ), ); } - if (threadPullRequestAutomationArmed(thread)) { + if (threadPullRequestAutomationArmed(thread) && !takesState) { found.push( blocked( "pull_request_automation", @@ -312,8 +353,9 @@ export function firstMoveBlock(refusals: ReadonlyArray) export function threadMoveRefusal( readModel: ThreadMoveView, thread: OrchestrationThread, + takes?: ThreadMoveTakes | null, ): string | null { - const refusals = threadMoveRefusals(readModel, thread); + const refusals = threadMoveRefusals(readModel, thread, takes); const block = firstMoveBlock(refusals); if (block !== null) return block.words; const first = refusals[0]; @@ -342,6 +384,9 @@ const FROZEN_THREAD_COMMANDS: ReadonlySet = new Se "thread.activity.append", "thread.effective-cwd.set", "thread.check-backs.set", + // What the provider reports of its goal as the move's stop pauses it: the + // goal bar must say what the provider holds, should the move be dropped. + "thread.goal.state.set", "thread.pull-request.link", "thread.diffstat.rebase", "thread.realtime.state.set", @@ -387,6 +432,9 @@ const WORK_START_COMMANDS: ReadonlySet = new Set([ "thread.continue-at-reset.fire", "thread.pull-request-automation.set", "thread.continue-at-reset.set", + // The queue doesn't drain while a move waits, or the thread is never free + // (docs/design/fleet.md, Part 3e, (e)); what goes into a running turn still does. + "thread.follow-up.send-queued", ]); /** Whether `command`, on its own thread, starts work there. */ @@ -400,6 +448,8 @@ function startsWork(command: OrchestrationCommand): boolean { ); case "thread.continue-at-reset.set": return command.enabled; + case "thread.follow-up.send-queued": + return command.steeredTurnId === undefined && command.steerIntoTurnId === undefined; default: return true; } @@ -476,17 +526,19 @@ export function decideMoveStart( ): ThreadMoveDecision { const pending = thread.pendingMove ?? null; const queuedRequestId = command.queuedRequestId; + // What the other computer said just now that it takes. + const takes = command.targetTakes; if (queuedRequestId === undefined) { if (pending !== null) { return refuse(`A move to ${pending.target.label} is already waiting. Cancel it first.`); } - const refusal = threadMoveRefusal(readModel, thread); + const refusal = threadMoveRefusal(readModel, thread, takes); if (refusal !== null) return refuse(refusal); } else { if (pending === null || pending.requestId !== queuedRequestId) { return refuse("That queued move was cancelled or replaced."); } - const refusals = threadMoveRefusals(readModel, thread); + const refusals = threadMoveRefusals(readModel, thread, takes); const block = firstMoveBlock(refusals); if (block !== null) return refuse(block.words); if (refusals.length > 0) return refuse(BUSY_WORDS); @@ -494,6 +546,16 @@ export function decideMoveStart( return refuse("This thread's agent hasn't stopped yet."); } } + // What its stop took: a queued move's, with what a stop planned here (a + // direct move whose session still runs) takes now. + // What an earlier move that didn't happen still owes the thread comes along. + const owed = thread.moveRestoreOwed ?? null; + const interrupted = + queuedRequestId !== undefined + ? mergeInterrupted(thread, pending?.interrupted) + : sessionStopped(thread) && owed === null + ? undefined + : mergeInterrupted(thread, owed?.interrupted); const started: PlannedEvent = { ...baseFor(thread.id), type: "thread.move-started", @@ -507,6 +569,8 @@ export function decideMoveStart( ...(pending?.batchId !== undefined && queuedRequestId !== undefined ? { batchId: pending.batchId } : {}), + ...(interrupted !== undefined ? { interrupted } : {}), + ...(takes !== undefined ? { targetTakes: takes } : {}), }, }; const queueEnded: PlannedEvent[] = @@ -531,11 +595,14 @@ export function decideMoveStart( command.createdAt, baseFor, ); + // The move holds what was owed now (its `interrupted`). + const absorbed = owed !== null ? [restoreSet(thread, null, command.createdAt, baseFor)] : []; if (sessionStopped(thread)) { - return [...cancelled, ...queueEnded, started]; + return [...cancelled, ...absorbed, ...queueEnded, started]; } return [ ...cancelled, + ...absorbed, started, { ...baseFor(thread.id), @@ -551,6 +618,51 @@ function currentPendingMove(thread: OrchestrationThread, requestId: string) { return pending !== null && pending.requestId === requestId ? pending : null; } +/** Records what a move that didn't happen owes the thread back, or (null) that it is paid. */ +function restoreSet( + thread: OrchestrationThread, + owed: ThreadMoveRestore | null, + at: string, + baseFor: EventBase, +): PlannedEvent { + return { + ...baseFor(thread.id), + type: "thread.move-restore-set", + payload: { threadId: thread.id, moveRestoreOwed: owed, updatedAt: at }, + }; +} + +/** + * What a move that ends without moving owes the thread (docs/design/fleet.md, + * Part 3e, "Put back"): what its stop took, and a send of the queued messages + * that waited for it. None when there is nothing to put back. + */ +function restoreOwedEvents( + thread: OrchestrationThread, + target: ThreadMoveTarget, + interrupted: ThreadMoveInterrupted | undefined, + at: string, + baseFor: EventBase, +): PlannedEvent[] { + // An archived or deleted thread is gone: nothing starts on it. + if (thread.deletedAt !== null || thread.archivedAt !== null) return []; + const queued = (thread.queuedFollowUps ?? []).length > 0; + if (interrupted === undefined && !queued) return []; + return [ + restoreSet( + thread, + { + target, + ...(interrupted !== undefined ? { interrupted } : {}), + ...(queued ? { queued: true as const } : {}), + at, + }, + at, + baseFor, + ), + ]; +} + /** Ending every runtime of the thread: "Stop and move now", and the barrier before a freeze. */ function sessionStopEvents( thread: OrchestrationThread, @@ -598,7 +710,7 @@ export function decideMoveQueue( ? [] : refuse(`A move to ${pending.target.label} is already waiting. Cancel it first.`); } - const refusals = threadMoveRefusals(readModel, thread); + const refusals = threadMoveRefusals(readModel, thread, command.targetTakes); const block = firstMoveBlock(refusals); if (block !== null) return refuse(block.words); // A command runs in the user's own terminal tab, which the server doesn't @@ -606,6 +718,11 @@ export function decideMoveQueue( if (command.mode === "stop-now" && refusals.some((entry) => entry.code === "command_run")) { return refuse(STOP_NOW_COMMAND_RUN_WORDS); } + // What an earlier move that didn't happen still owes comes along, and what + // "Stop and move now" stops is recorded before it is gone. + const owed = thread.moveRestoreOwed ?? null; + const interrupted = + command.mode === "stop-now" ? mergeInterrupted(thread, owed?.interrupted) : owed?.interrupted; const queued: PlannedEvent = { ...baseFor(thread.id), type: "thread.move-queued", @@ -622,12 +739,15 @@ export function decideMoveQueue( waitsFor: moveWaitsOf(refusals), hold: null, ...(command.batchId !== undefined ? { batchId: command.batchId } : {}), + ...(interrupted !== undefined ? { interrupted } : {}), + ...(command.targetTakes !== undefined ? { targetTakes: command.targetTakes } : {}), }, }, }; + const absorbed = owed !== null ? [restoreSet(thread, null, command.createdAt, baseFor)] : []; return command.mode === "stop-now" - ? [queued, ...sessionStopEvents(thread, command.createdAt, baseFor)] - : [queued]; + ? [...absorbed, queued, ...sessionStopEvents(thread, command.createdAt, baseFor)] + : [...absorbed, queued]; } /** @@ -645,10 +765,11 @@ export function decideMoveSetMode( ): ThreadMoveDecision { const pending = currentPendingMove(thread, command.requestId); if (pending === null || pending.mode === command.mode) return []; - const refusals = threadMoveRefusals(readModel, thread); + const refusals = threadMoveRefusals(readModel, thread, pending.targetTakes); if (refusals.some((entry) => entry.code === "command_run")) { return refuse(STOP_NOW_COMMAND_RUN_WORDS); } + const interrupted = mergeInterrupted(thread, pending.interrupted); const modeSet: PlannedEvent = { ...baseFor(thread.id), type: "thread.move-mode-set", @@ -656,6 +777,7 @@ export function decideMoveSetMode( threadId: thread.id, requestId: command.requestId, mode: command.mode, + ...(interrupted !== undefined ? { interrupted } : {}), updatedAt: command.createdAt, }, }; @@ -670,7 +792,8 @@ export function decideMoveUnqueue( command: CommandOf<"thread.move.unqueue">, baseFor: EventBase, ): ThreadMoveDecision { - if (currentPendingMove(thread, command.requestId) === null) return []; + const pending = currentPendingMove(thread, command.requestId); + if (pending === null) return []; return [ { ...baseFor(thread.id), @@ -682,6 +805,7 @@ export function decideMoveUnqueue( endedAt: command.createdAt, }, }, + ...restoreOwedEvents(thread, pending.target, pending.interrupted, command.createdAt, baseFor), ]; } @@ -698,21 +822,31 @@ export function decideMoveQuiesce( ): ThreadMoveDecision { const pending = currentPendingMove(thread, command.requestId); if (pending === null) return []; - const refusals = threadMoveRefusals(readModel, thread); + const refusals = threadMoveRefusals(readModel, thread, pending.targetTakes); const block = firstMoveBlock(refusals); if (block !== null) return refuse(block.words); if (refusals.length > 0) return refuse(BUSY_WORDS); + // What the stop takes, recorded before it is gone; only ever added to, so a + // move that went back to waiting doesn't forget its goal was working. + const interrupted = mergeInterrupted(thread, pending.interrupted); + const quiescing: PlannedEvent = { + ...baseFor(thread.id), + type: "thread.move-quiescing", + payload: { + threadId: thread.id, + requestId: command.requestId, + ...(interrupted !== undefined ? { interrupted } : {}), + updatedAt: command.createdAt, + }, + }; if (pending.stage === "quiescing") { - return sessionStopped(thread) ? [] : sessionStopEvents(thread, command.createdAt, baseFor); + if (sessionStopped(thread)) return []; + return [ + ...(sameInterrupted(interrupted, pending.interrupted) ? [] : [quiescing]), + ...sessionStopEvents(thread, command.createdAt, baseFor), + ]; } - return [ - { - ...baseFor(thread.id), - type: "thread.move-quiescing", - payload: { threadId: thread.id, requestId: command.requestId, updatedAt: command.createdAt }, - }, - ...sessionStopEvents(thread, command.createdAt, baseFor), - ]; + return [quiescing, ...sessionStopEvents(thread, command.createdAt, baseFor)]; } /** @@ -805,6 +939,10 @@ export function decideMoveQueueEnd( }, }, }, + // An archived or deleted thread gets nothing back. + ...(command.reason === "blocked" + ? restoreOwedEvents(thread, pending.target, pending.interrupted, command.createdAt, baseFor) + : []), ]; } @@ -903,6 +1041,7 @@ export function decideMoveAbort( }, }, }, + ...restoreOwedEvents(thread, move.target, move.interrupted, command.createdAt, baseFor), ]; } @@ -925,6 +1064,50 @@ export function decideMoveComplete( movedAt: command.createdAt, }, }, + ...readOnlyCopyEvents(thread, command.createdAt, baseFor), + ]; +} + +/** + * The read-only copy a moved thread leaves keeps nothing that acts for it + * (docs/design/fleet.md, Part 3e): its queued messages went with it, and its + * pull request switches are off, so neither the queue nor the watcher here + * ever works for a thread that lives on the other computer now. + */ +function readOnlyCopyEvents( + thread: OrchestrationThread, + at: string, + baseFor: EventBase, +): PlannedEvent[] { + const unqueued: PlannedEvent[] = (thread.queuedFollowUps ?? []).map((entry) => ({ + ...baseFor(thread.id), + type: "thread.follow-up-unqueued", + payload: { + threadId: thread.id, + messageId: entry.messageId, + reason: "cancelled", + createdAt: at, + }, + })); + const switchesOff = (pullRequestNumber?: number): PlannedEvent => ({ + ...baseFor(thread.id), + type: "thread.pull-request-automation-changed", + payload: { + threadId: thread.id, + ...(pullRequestNumber !== undefined ? { pullRequestNumber } : {}), + autoFix: false, + autoMerge: null, + updatedAt: at, + }, + }); + const own = thread.pullRequestAutoFix || thread.pullRequestAutoMerge !== null; + const linked = (thread.linkedPullRequests ?? []).filter( + (entry) => entry.autoFix || entry.autoMerge !== null, + ); + return [ + ...unqueued, + ...(own ? [switchesOff()] : []), + ...linked.map((entry) => switchesOff(entry.number)), ]; } @@ -994,6 +1177,7 @@ export function decideThreadImport( type: "thread.activity-appended", payload: { threadId: command.threadId, activity: { ...activity, turnId: null } }, })); + const arrival = command.arrival; const boundary: PlannedEvent = { ...base(), type: "thread.activity-appended", @@ -1011,13 +1195,292 @@ export function decideThreadImport( movedAt: command.movedFrom.movedAt, // 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 } + : {}), + ...(arrival !== undefined && arrival.left.length > 0 ? { left: arrival.left } : {}), }, turnId: null, createdAt: command.createdAt, }, }, }; - return [created, ...messages, ...activities, boundary]; + return [created, ...messages, ...activities, ...importedState(command, base), boundary]; +} + +/** + * What a moved thread had going, written with it (docs/design/fleet.md, Part + * 3e): its goal as it arrives, its pull requests and their switches, its + * plans, and its queue (the arrival message first). The queue's events are + * marked `imported`: nothing sends on them; the move's own kick sends its head. + */ +function importedState( + command: CommandOf<"thread.import">, + base: () => Omit, +): PlannedEvent[] { + const threadId = command.threadId; + const at = command.createdAt; + const events: PlannedEvent[] = []; + if (command.goal !== undefined) { + events.push({ + ...base(), + type: "thread.goal-state-set", + payload: { threadId, goal: { ...command.goal, threadId }, updatedAt: at }, + }); + } + const pullRequests = command.pullRequests; + if (pullRequests !== undefined) { + for (const linked of pullRequests.linked) { + events.push({ + ...base(), + type: "thread.pull-request-linked", + payload: { threadId, number: linked.number, url: linked.url, linkedAt: at }, + }); + if (linked.autoFix || linked.autoMerge !== null) { + events.push({ + ...base(), + type: "thread.pull-request-automation-changed", + payload: { + threadId, + pullRequestNumber: linked.number, + autoFix: linked.autoFix, + autoMerge: linked.autoMerge, + updatedAt: at, + }, + }); + } + } + if (pullRequests.autoFix || pullRequests.autoMerge !== null) { + events.push({ + ...base(), + type: "thread.pull-request-automation-changed", + payload: { + threadId, + autoFix: pullRequests.autoFix, + autoMerge: pullRequests.autoMerge, + updatedAt: at, + }, + }); + } + } + for (const proposedPlan of command.proposedPlans ?? []) { + events.push({ + ...base(), + type: "thread.proposed-plan-upserted", + payload: { threadId, proposedPlan }, + }); + } + const message = command.arrival?.message; + const queue: OrchestrationQueuedFollowUp[] = [ + ...(message !== undefined + ? [ + { + messageId: message.messageId, + text: message.text, + attachments: [], + afterMove: true as const, + runtimeMode: command.runtimeMode, + interactionMode: command.interactionMode, + createdAt: at, + }, + ] + : []), + ...(command.queuedFollowUps ?? []), + ]; + for (const followUp of queue) { + events.push({ + ...base(), + type: "thread.follow-up-queued", + payload: { threadId, followUp, imported: true }, + }); + } + return events; +} + +/** + * Puts back what a move that didn't happen took (docs/design/fleet.md, Part + * 3e, "Put back"), from what was recorded when it stopped the agent, not + * from how the goal reads now: a goal that was working is on again (one that + * finished since stays finished, one the user paused stays paused), the + * agent is told what it had going (queued ahead of the user's messages, and + * sent like them), and the queued messages that waited are sent. One + * decision, which clears what was owed, so it is paid once. + */ +export function decideMoveRestore( + thread: OrchestrationThread, + command: CommandOf<"thread.move.restore">, + baseFor: EventBase, +): ThreadMoveDecision { + const owed = thread.moveRestoreOwed ?? null; + // Paid already, or a newer record since: no news. + if (owed === null || owed.at !== command.at) return []; + const at = command.createdAt; + // The last of it: its message went, the queue is through, the provider + // holds the goal again. + if (command.finished === true) { + return isRestorePaid(owed) ? [restoreSet(thread, null, at, baseFor)] : []; + } + if (isRestorePaid(owed)) return []; + const events: PlannedEvent[] = []; + // Paused by the move's stop (Codex): on again. Claude can't pause one, so + // it still reads active; the agent's message brings it back to work, and + // the provider is given it once that is done (`goalOwed`). + const goal = thread.goal; + const goalBack = + owed.interrupted?.goalActive === true && + goal !== null && + (goal.status === "active" || goal.status === "paused"); + if (goalBack && goal !== null && goal.status === "paused") { + events.push({ + ...baseFor(thread.id), + type: "thread.goal-state-set", + payload: { + threadId: thread.id, + goal: { ...goal, status: "active", updatedAt: at }, + updatedAt: at, + }, + }); + } + if (command.message !== undefined) { + events.push({ + ...baseFor(thread.id), + type: "thread.follow-up-queued", + payload: { + threadId: thread.id, + followUp: { + messageId: command.message.messageId, + text: command.message.text, + attachments: [], + afterMove: true, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + createdAt: at, + }, + }, + }); + } + // Paid; what is still to come stays on record until it is done, so a + // restart before the message went (or before the goal was given) finishes it. + const told = command.message?.messageId; + events.push( + restoreSet( + thread, + told !== undefined || goalBack + ? { + target: owed.target, + ...(told !== undefined ? { told } : {}), + ...(goalBack ? { goalOwed: true as const } : {}), + at: owed.at, + } + : null, + at, + baseFor, + ), + ); + return events; +} + +/** + * Whether a move's record of what it owes back is already paid, and only + * its last steps are left (ThreadMoveRestore.told, goalOwed). + */ +export const isRestorePaid = (owed: ThreadMoveRestore) => + owed.interrupted === undefined && owed.queued !== true; + +/** + * Resume, on a moved thread whose agent hasn't been given the conversation + * yet (docs/design/fleet.md, Part 3e, (a)): no provider call, which would + * set the goal on an agent that doesn't know the thread. The goal reads + * active, and a message for the agent is queued; once it is sent, the + * reactor gives the provider the goal (what is left of its budget). Null: + * not that case, decided as any other goal change. + */ +export function decideMovedGoalResume( + thread: OrchestrationThread, + command: CommandOf<"thread.goal.set">, + baseFor: EventBase, +): ThreadMoveDecision | null { + const current = thread.goal; + // A resume, an edit or a new goal: anything that would set the goal working. + const working = command.status === undefined || command.status === "active"; + const objective = command.objective ?? current?.objective; + if ( + !working || + objective === undefined || + (thread.movedFrom ?? null) === null || + thread.historySeedOwed !== true || + (command.objective === undefined && current?.status === "active") + ) { + return null; + } + const at = command.createdAt; + const goal = { + threadId: thread.id, + objective, + status: "active" as const, + tokenBudget: + command.tokenBudget !== undefined + ? command.tokenBudget + : command.objective !== undefined + ? null + : (current?.tokenBudget ?? null), + tokensUsed: command.objective !== undefined ? 0 : (current?.tokensUsed ?? 0), + timeUsedSeconds: command.objective !== undefined ? 0 : (current?.timeUsedSeconds ?? 0), + createdAt: command.objective !== undefined ? at : (current?.createdAt ?? at), + updatedAt: at, + }; + return [ + { + ...baseFor(thread.id), + type: "thread.goal-state-set", + payload: { threadId: thread.id, goal, updatedAt: at }, + }, + { + ...baseFor(thread.id), + type: "thread.follow-up-queued", + payload: { + threadId: thread.id, + followUp: { + messageId: MessageId.make(derivedUuid("move-goal-resume", command.commandId)), + text: resumedGoalMessageText(objective), + attachments: [], + afterMove: true, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + createdAt: at, + }, + }, + }, + ]; +} + +/** + * The message a move that didn't happen leaves for the thread's agent, or + * null: what its stop took, from the record of it. + */ +export function restoreMessageText( + thread: Pick, + owed: ThreadMoveRestore, + now: string, + canSetCheckBacks: boolean, +): string | null { + const goal = thread.goal; + const goalWorking = + owed.interrupted?.goalActive === true && + goal !== null && + (goal.status === "active" || goal.status === "paused"); + return arrivalMessageText({ + kind: "stayed", + from: "", + to: owed.target.label, + goal: goalWorking && goal !== null ? { objective: goal.objective } : null, + // Saved ones too: the agent's next session restores them, and the + // message has it look (CronList) before it sets any again. + checkBacks: owed.interrupted?.checkBacks ?? [], + canSetCheckBacks, + now, + }); } export function decideHistorySeedDelivered( diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index e8b3e8d32..50060df01 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -63,6 +63,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( sentFrom: Schema.NullOr(Schema.fromJsonString(MessageSentFrom)), trigger: Schema.NullOr(MessageTrigger), notSent: Schema.NullOr(Schema.Number), + afterMove: Schema.NullOr(Schema.Number), }), ); @@ -98,6 +99,7 @@ function toProjectionThreadMessage( ...(row.sentFrom !== null ? { sentFrom: row.sentFrom } : {}), ...(row.trigger !== null ? { trigger: row.trigger } : {}), ...(row.notSent === 1 ? { notSent: true as const } : {}), + ...(row.afterMove === 1 ? { afterMove: true as const } : {}), }; } @@ -143,6 +145,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { sent_from, message_trigger, not_sent, + after_move, is_streaming, created_at, updated_at @@ -187,6 +190,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { ${row.sentFrom !== undefined ? JSON.stringify(row.sentFrom) : null}, ${row.trigger ?? null}, ${row.notSent === true ? 1 : null}, + ${row.afterMove === true ? 1 : null}, ${row.isStreaming ? 1 : 0}, ${row.createdAt}, ${row.updatedAt} @@ -229,6 +233,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { sent_from = COALESCE(projection_thread_messages.sent_from, excluded.sent_from), message_trigger = COALESCE(projection_thread_messages.message_trigger, excluded.message_trigger), not_sent = COALESCE(excluded.not_sent, projection_thread_messages.not_sent), + after_move = COALESCE(excluded.after_move, projection_thread_messages.after_move), is_streaming = excluded.is_streaming, created_at = CASE WHEN ${appendText ? 1 : 0} = 1 THEN projection_thread_messages.created_at @@ -278,6 +283,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { sent_from AS "sentFrom", message_trigger AS "trigger", not_sent AS "notSent", + after_move AS "afterMove", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -318,6 +324,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { sent_from AS "sentFrom", message_trigger AS "trigger", not_sent AS "notSent", + after_move AS "afterMove", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index f7be734fd..141832d4c 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -33,6 +33,7 @@ import { ThreadPendingMove, ThreadMovedFrom, ThreadMoveOutcome, + ThreadMoveRestore, ThreadRemoteOrigin, OrchestrationOutsideWork, OutsideAgentRef, @@ -69,6 +70,7 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields( pendingMove: Schema.NullOr(Schema.fromJsonString(ThreadPendingMove)), movedFrom: Schema.NullOr(Schema.fromJsonString(ThreadMovedFrom)), lastMoveOutcome: Schema.NullOr(Schema.fromJsonString(ThreadMoveOutcome)), + moveRestoreOwed: Schema.NullOr(Schema.fromJsonString(ThreadMoveRestore)), roomContext: Schema.fromJsonString( Schema.Record(Schema.String, OrchestrationRoomContextCursor), ), @@ -133,6 +135,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_move_json, moved_from_json, last_move_outcome_json, + move_restore_owed_json, history_seed_owed, history_seed_message_id, native_session, @@ -203,6 +206,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.pendingMove ? JSON.stringify(row.pendingMove) : null}, ${row.movedFrom ? JSON.stringify(row.movedFrom) : null}, ${row.lastMoveOutcome ? JSON.stringify(row.lastMoveOutcome) : null}, + ${row.moveRestoreOwed ? JSON.stringify(row.moveRestoreOwed) : null}, ${row.historySeedOwed ?? 0}, ${row.historySeedMessageId ?? null}, ${row.nativeSession ?? null}, @@ -265,6 +269,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_move_json = excluded.pending_move_json, 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, history_seed_owed = excluded.history_seed_owed, history_seed_message_id = excluded.history_seed_message_id, native_session = excluded.native_session, @@ -334,6 +339,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", @@ -405,6 +411,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pending_move_json AS "pendingMove", moved_from_json AS "movedFrom", last_move_outcome_json AS "lastMoveOutcome", + move_restore_owed_json AS "moveRestoreOwed", history_seed_owed AS "historySeedOwed", history_seed_message_id AS "historySeedMessageId", native_session AS "nativeSession", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index d4613280e..2c157f546 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -136,6 +136,7 @@ import Migration0113 from "./Migrations/113_LinkMoveStagedApproval.ts"; import Migration0114 from "./Migrations/114_LinkMoveAbortCode.ts"; import Migration0115 from "./Migrations/115_ThreadNativeSession.ts"; import Migration0116 from "./Migrations/116_ProjectLeadThread.ts"; +import Migration0117 from "./Migrations/117_ThreadMoveCarry.ts"; /** * Migration loader with all migrations defined inline. @@ -264,6 +265,7 @@ export const migrationEntries = [ [114, "LinkMoveAbortCode", Migration0114], [115, "ThreadNativeSession", Migration0115], [116, "ProjectLeadThread", Migration0116], + [117, "ThreadMoveCarry", Migration0117], ] 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/117_ThreadMoveCarry.ts b/apps/server/src/persistence/Migrations/117_ThreadMoveCarry.ts new file mode 100644 index 000000000..6a00ac755 --- /dev/null +++ b/apps/server/src/persistence/Migrations/117_ThreadMoveCarry.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * A thread moves with what it had going (docs/design/fleet.md, Part 3e): + * + * - `move_restore_owed_json` on `projection_threads`: what a move that didn't + * happen owes the thread back (`OrchestrationThread.moveRestoreOwed`), null + * once paid and for every thread before; + * - `after_move` on `projection_thread_messages`: 1 on a message Threadlines + * wrote for the agent when the thread moved or its move didn't happen + * (`OrchestrationMessage.afterMove`), null on every other. + * + * New nullable columns; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE projection_threads ADD COLUMN move_restore_owed_json TEXT`; + yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN after_move INTEGER`; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index 27f59f4ad..01e0f023a 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -81,6 +81,8 @@ export const ProjectionThreadMessage = Schema.Struct({ trigger: Schema.optional(MessageTrigger), /** See OrchestrationMessage.notSent. Once set, kept. */ notSent: Schema.optional(Schema.Literal(true)), + /** See OrchestrationMessage.afterMove. Once set, kept. */ + afterMove: Schema.optional(Schema.Literal(true)), isStreaming: Schema.Boolean, createdAt: IsoDateTime, updatedAt: IsoDateTime, diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index d2624b365..0fb9b7db4 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -36,6 +36,7 @@ import { ThreadMovedFrom, ThreadNativeSession, ThreadMoveOutcome, + ThreadMoveRestore, ThreadRemoteOrigin, OrchestrationOutsideWork, OutsideAgentRef, @@ -206,6 +207,8 @@ export const ProjectionThread = Schema.Struct({ movedFrom: Schema.optional(Schema.NullOr(ThreadMovedFrom)), /** See `OrchestrationThread.lastMoveOutcome`. Absent or null reads as none. */ lastMoveOutcome: Schema.optional(Schema.NullOr(ThreadMoveOutcome)), + /** See `OrchestrationThread.moveRestoreOwed`. Absent or null reads as none. */ + moveRestoreOwed: Schema.optional(Schema.NullOr(ThreadMoveRestore)), /** See `OrchestrationThread.historySeedOwed`, as 0 or 1. Absent or null reads as 0. */ historySeedOwed: Schema.optional(Schema.NullOr(NonNegativeInt)), /** See `OrchestrationThread.historySeedMessageId`. Absent or null reads as none. */ diff --git a/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts b/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts index b27e5e900..3c3663be0 100644 --- a/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts @@ -40,6 +40,9 @@ describe("Claude check-backs", () => { recurring: true, schedule: "every 5 minutes", description: "Look at the deploy", + // What a moved thread's agent is told to set again (fleet.md, Part 3e). + prompt: "Look at the deploy", + cron: "*/5 * * * *", durable: false, }, { @@ -48,6 +51,8 @@ describe("Claude check-backs", () => { exact: true, recurring: false, description: "Waiting for CI on PR #502", + prompt: "Check CI on #502", + cron: "42 15 20 10 *", durable: false, }, ]); diff --git a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts index 8b8c3c0ee..1d61e52cf 100644 --- a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts +++ b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts @@ -11,7 +11,11 @@ * and turns each reported list into check-backs, and tells a turn that a * fired check-back started from any other. */ -import type { RuntimeCheckBack, TurnTrigger } from "@threadlines/contracts"; +import { + CHECK_BACK_PROMPT_MAX_CHARS, + type RuntimeCheckBack, + type TurnTrigger, +} from "@threadlines/contracts"; import { nextCronMatch } from "@threadlines/shared/cronSchedule"; /** One entry of the Stop hook's `session_crons`. */ @@ -71,6 +75,15 @@ function clip(text: string): string | undefined { : flat; } +/** A check-back's prompt as kept (OrchestrationCheckBack.prompt): trimmed, and clipped. */ +function keptPrompt(text: string): string | undefined { + const trimmed = text.trim(); + if (trimmed.length === 0) return undefined; + return trimmed.length > CHECK_BACK_PROMPT_MAX_CHARS + ? `${trimmed.slice(0, CHECK_BACK_PROMPT_MAX_CHARS - 1)}…` + : trimmed; +} + function promptMatches(full: string, reported: string): boolean { const clipped = reported.replace(CLIPPED_PROMPT_MARKER, ""); return clipped === reported ? full === reported : full.startsWith(clipped); @@ -204,6 +217,10 @@ export function claudeCheckBacksFromSessionCrons( state.prompts.set(cron.id, prompt); const description = clip(wakeup?.reason ?? prompt); const schedule = cron.recurring ? record?.schedule : undefined; + // What the agent is told when it comes back, and the cron it set: what a + // moved thread's agent sets again elsewhere (docs/design/fleet.md, Part 3e). + const kept = keptPrompt(prompt); + const cronExpression = asString(cron.schedule)?.trim(); checkBacks.push({ id: cron.id, scheduledFor: new Date(fire.ms).toISOString(), @@ -211,6 +228,8 @@ export function claudeCheckBacksFromSessionCrons( recurring: cron.recurring, ...(schedule ? { schedule } : {}), ...(description ? { description } : {}), + ...(kept ? { prompt: kept } : {}), + ...(cronExpression ? { cron: cronExpression } : {}), // A job neither set by a CronCreate nor a wake-up this session saw came // from disk (a durable job the CLI restored): it outlives the session. durable: record ? record.durable : wakeup === undefined, diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 84bc08765..5cd30abee 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -11016,6 +11016,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( activeTurnSteering: "supported", threadGoals: "supported", threadGoalPause: "unsupported", + // `/goal` takes only the condition. + threadGoalBudget: "unsupported", + checkBacks: "supported", earlySessionStart: "supported", }, startSession, diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 7824c4f03..900d079fd 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -2430,6 +2430,29 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }, ); + const getThreadGoal: ProviderServiceShape["getThreadGoal"] = Effect.fn("getThreadGoal")( + function* (rawInput) { + const input = yield* decodeInputOrValidationError({ + operation: "ProviderService.getThreadGoal", + schema: ProviderClearThreadGoalServiceInput, + payload: rawInput, + }); + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.getThreadGoal", + allowRecovery: false, + }); + if ( + !routed.isActive || + routed.adapter.capabilities.threadGoals !== "supported" || + routed.adapter.getThreadGoal === undefined + ) { + return null; + } + return yield* routed.adapter.getThreadGoal(routed.threadId); + }, + ); + const pauseThreadGoalForStop: ProviderServiceShape["pauseThreadGoalForStop"] = Effect.fn( "pauseThreadGoalForStop", )(function* (rawInput) { @@ -3272,6 +3295,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( compactContext, setThreadGoal, pauseThreadGoalForStop, + getThreadGoal, clearThreadGoal, respondToRequest, respondToUserInput, diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 8760838ac..71f25068d 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -241,6 +241,7 @@ describe("ProviderSessionReaper", () => { compactContext: () => unsupported(), setThreadGoal: () => unsupported(), pauseThreadGoalForStop: () => Effect.succeed(null), + getThreadGoal: () => Effect.succeed(null), clearThreadGoal: () => unsupported(), respondToRequest: () => unsupported(), respondToUserInput: () => unsupported(), diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index d19d48dee..0fce5bded 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -122,6 +122,19 @@ export interface ProviderAdapterCapabilities { */ readonly threadGoalPause?: ProviderThreadGoalsMode; + /** + * Declares whether a supported goal takes a token budget. Absent means it + * does. Claude's don't: a goal with one arrives paused when a thread moves + * to it (docs/design/fleet.md, Part 3e). + */ + readonly threadGoalBudget?: ProviderThreadGoalsMode; + + /** + * Declares whether the agent sets itself times to come back (check-backs: + * Claude's ScheduleWakeup and CronCreate). Absent means it doesn't. + */ + readonly checkBacks?: ProviderThreadGoalsMode; + /** * Declares whether this adapter can open a session as a provider-side fork * of another thread's history (`ProviderSessionStartInput.forkFrom`). diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 9e17a6775..7f56ab4c0 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -272,6 +272,15 @@ export interface ProviderServiceShape { readonly modelSelection?: ModelSelection; }) => Effect.Effect; + /** + * The goal the thread's live provider session holds, as the provider says + * it; null when it holds none, or there is no live goal-capable session. + * Never recovers a cold session. + */ + readonly getThreadGoal: (input: { + readonly threadId: ThreadId; + }) => Effect.Effect; + /** * Pause an active goal before stopping its live provider session. * Never recovers a cold session. Returns the authoritative provider state diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 07e77f48f..083cbed54 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -27,6 +27,7 @@ import { LinkMoveRepositoryLive } from "./links/LinkMoveRepository.ts"; import { LinkMovesLive } from "./links/LinkMoves.ts"; import { MoveQueueLive } from "./moves/MoveQueue.ts"; import { ThreadMoveBatchRepositoryLive } from "./moves/ThreadMoveBatchRepository.ts"; +import { ThreadActionGateLive } from "./moves/ThreadActionGate.ts"; import { ThreadMovesLive } from "./moves/ThreadMoves.ts"; import { layer as ProcessRunnerLive } from "./processRunner.ts"; import { ProjectSetupRepositoryLive } from "./projectSetup/ProjectSetupRepository.ts"; @@ -392,8 +393,10 @@ const ReactorLayerLive = Layer.empty.pipe( Layer.provideMerge(PullRequestAutomationWatcherLive), Layer.provideMerge( // Adapters ask it before the provider's own scheduling tools (step 3 of - // docs/design/assistants.md). - Layer.mergeAll(ThreadPullRequestLinkerLive, OutsideWorkLookupLive), + // docs/design/assistants.md). The pull request watcher and the move share + // the action gate: no act for a thread lands across its freeze + // (docs/design/fleet.md, Part 3e). + Layer.mergeAll(ThreadPullRequestLinkerLive, OutsideWorkLookupLive, ThreadActionGateLive), ), ); diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 34c70f363..6ac99605d 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -1,6 +1,7 @@ import { type ComputerLinkPendingRequest, EventId, + GENERAL_CHATS_PROJECT_ID, MessageId, ORCHESTRATION_WS_METHODS, type OrchestrationEvent, @@ -41,6 +42,8 @@ import { THREAD_REF, THREAD_TITLE, LOCAL_ENVIRONMENT_ID, + PROJECT_ID, + createUserMessage, NOW_ISO, rpcHarness, WIDE_FOOTER_VIEWPORT, @@ -101,6 +104,7 @@ function withMoveCapabilities( readonly threadMoveQueue?: true; readonly threadMoveBatch?: true; readonly threadMoveStagedApproval?: true; + readonly threadMoveState?: true; }, ): void { withComputerLinksFixture(nextFixture); @@ -145,6 +149,37 @@ function withTestThread( }; } +/** What didn't come along with a thread that moved here, as the server says it. */ +const MOVED_IN_LEFT_SENTENCE = + "Auto-fix is off here: this computer already has a branch named `fix-login`, so pushes from this thread wouldn't reach pull request #212."; + +/** The snapshot with this computer's General Chats, holding the threads `threadIds`. */ +function withGeneralChats( + snapshot: OrchestrationReadModel, + threadIds: ReadonlyArray, +): OrchestrationReadModel { + return { + ...snapshot, + projects: [ + ...snapshot.projects, + { + id: GENERAL_CHATS_PROJECT_ID, + kind: "general-chat" as const, + title: "General Chats", + workspaceRoot: "/repo/general-chats", + defaultModelSelection: null, + scripts: [], + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + deletedAt: null, + }, + ], + threads: snapshot.threads.map((thread) => + threadIds.includes(thread.id) ? { ...thread, projectId: GENERAL_CHATS_PROJECT_ID } : thread, + ), + }; +} + /** Where the test thread could go: Windows PC can't take it, Mac mini asks first. */ const FLEET_MOVE_PREVIEW: ThreadMovePreview = { changes: { @@ -327,8 +362,17 @@ describe("ChatView (full app): moving a thread to another computer", () => { }), ); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); + // Not for a General Chats thread: this computer doesn't move those. + expect( + readThreadMoveOffered({ + environmentId: LOCAL_ENVIRONMENT_ID, + projectId: GENERAL_CHATS_PROJECT_ID, + }), + ).toBe(false); await openSidebarThreadMenu(THREAD_ID); await expect .element(page.getByText("Move to another computer", { exact: true })) @@ -384,7 +428,9 @@ describe("ChatView (full app): moving a thread to another computer", () => { await waitForServerConfigToApply(); await saveMacMini("connected"); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); await openCommandPaletteFromTrigger(); await page @@ -466,6 +512,170 @@ describe("ChatView (full app): moving a thread to another computer", () => { } }); + it("says what comes along, and what won't work there for the agent picked", async () => { + setPrimaryLinksSnapshot( + fleetLinksSnapshot({ + outbound: [fleetOutboundLink(FLEET_OFFLINE_ENVIRONMENT_ID, "Mac mini")], + }), + ); + const macMini = FLEET_MOVE_PREVIEW.targets[1]!; + const codexOnly = "Codex on Mac mini can't set check-backs. It's told once what was planned."; + const github = "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in."; + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-move-brings" as MessageId, + targetText: "move brings", + }), + configureFixture: (fixture) => + withMoveCapabilities(fixture, { threadMove: true, threadMoveState: true }), + resolveRpc: (body) => { + if (body._tag !== WS_METHODS.movesPreview) return undefined; + return { + ...FLEET_MOVE_PREVIEW, + brings: [ + { words: "Its goal carries on there." }, + { words: "2 queued messages are sent there." }, + ], + targets: [ + { + ...macMini, + agents: [ + ...macMini.agents, + { + instanceId: "claudeAgent", + name: "Claude", + billing: "Claude Max", + driver: "claudeAgent", + models: [{ model: "claude-opus-5-5", name: "Opus 5.5" }], + }, + ], + notes: [{ words: codexOnly, instanceIds: ["codex"] }, { words: github }], + }, + ], + } satisfies ThreadMovePreview; + }, + }); + + const linesOf = (testId: string) => + Array.from(document.querySelectorAll(`[data-testid="${testId}"]`)).map( + (line) => line.textContent, + ); + try { + await waitForServerConfigToApply(); + await saveMacMini("connected"); + await openCommandPaletteFromTrigger(); + await page + .getByTestId("command-palette") + .getByText("Move to another computer", { exact: true }) + .click(); + const dialog = page.getByTestId("thread-move-dialog"); + await expect + .element(dialog.getByTestId("thread-move-agent")) + .toMatchTextContent("Codex · GPT-5"); + // Under the agent: what comes along, then what won't work as it did. + await expect.element(dialog.getByTestId("thread-move-carries")).toBeVisible(); + expect(linesOf("thread-move-brings")).toEqual([ + "Its goal carries on there.", + "2 queued messages are sent there.", + ]); + expect(linesOf("thread-move-note")).toEqual([codexOnly, github]); + + // Claude picked: the note about Codex goes, the one for any agent stays. + await dialog.getByTestId("thread-move-agent").click(); + await page.getByRole("option", { name: "Opus 5.5" }).click(); + await expect + .element(dialog.getByTestId("thread-move-agent")) + .toMatchTextContent("Claude · Opus 5.5"); + await vi.waitFor(() => expect(linesOf("thread-move-note")).toEqual([github])); + expect(linesOf("thread-move-brings")).toHaveLength(2); + } finally { + await mounted.cleanup(); + } + }); + + it("offers a General Chats thread where its computer moves them, landing in General chats with its files", async () => { + setPrimaryLinksSnapshot( + fleetLinksSnapshot({ + outbound: [fleetOutboundLink(FLEET_OFFLINE_ENVIRONMENT_ID, "Mac mini")], + }), + ); + const macMini = FLEET_MOVE_PREVIEW.targets[1]!; + const chatId = "thread-move-general-chat" as ThreadId; + const withChat = withGeneralChats( + addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-move-general-chat" as MessageId, + targetText: "move general chat", + }), + chatId, + ), + [chatId], + ); + const previews: Array = []; + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: { + ...withChat, + threads: withChat.threads.map((thread) => + thread.id === chatId ? { ...thread, title: "Best way to store passkeys" } : thread, + ), + }, + configureFixture: (fixture) => + withMoveCapabilities(fixture, { threadMove: true, threadMoveState: true }), + resolveRpc: (body) => { + if (body._tag !== WS_METHODS.movesPreview) return undefined; + previews.push(body); + return { + folder: { files: 14, bytes: 48_000 }, + targets: [{ ...macMini, projectName: "General chats" }], + } satisfies ThreadMovePreview; + }, + }); + + try { + await waitForServerConfigToApply(); + await saveMacMini("connected"); + await vi.waitFor(() => { + expect( + readThreadMoveOffered({ + environmentId: LOCAL_ENVIRONMENT_ID, + projectId: GENERAL_CHATS_PROJECT_ID, + }), + ).toBe(true); + }); + // The chat's own row menu, in the General Chats list, offers the move. + await page.getByTestId("rail-chats").click(); + const row = page + .getByTestId("chats-list-row") + .filter({ hasText: "Best way to store passkeys" }); + await expect.element(row).toBeVisible(); + const rect = row.element().getBoundingClientRect(); + row.element().dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: rect.left + 20, + clientY: rect.top + 8, + }), + ); + await page.getByText("Move to another computer", { exact: true }).click(); + const dialog = page.getByTestId("thread-move-dialog"); + await expect + .element(dialog.getByTestId("thread-move-landing")) + .toHaveTextContent("Lands in General chats on Mac mini · 14 files"); + // No branch: no changes line, and nothing staged to speak of. + const preview = dialog.getByTestId("thread-move-preview"); + await expect.element(preview).toMatchTextContent("Your copy here stays, read-only."); + expect(preview.element().textContent).not.toContain("Staged changes"); + expect(dialog.getByTestId("thread-move-changes").elements()).toHaveLength(0); + await expect.element(dialog.getByTestId("thread-move-confirm")).toBeEnabled(); + expect(previews).toEqual([expect.objectContaining({ threadId: chatId })]); + } finally { + await mounted.cleanup(); + } + }); + it("opens the thread's menu from its title in the header, by click or keyboard", async () => { setPrimaryLinksSnapshot( fleetLinksSnapshot({ @@ -496,7 +706,9 @@ describe("ChatView (full app): moving a thread to another computer", () => { await waitForServerConfigToApply(); await saveMacMini("connected"); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); const title = page.getByRole("button", { name: `${THREAD_TITLE}, thread menu` }); @@ -582,7 +794,9 @@ describe("ChatView (full app): moving a thread to another computer", () => { await waitForServerConfigToApply(); await saveMacMini("connected"); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); await openCommandPaletteFromTrigger(); await page @@ -696,7 +910,9 @@ describe("ChatView (full app): moving a thread to another computer", () => { await waitForServerConfigToApply(); await saveMacMini("disconnected"); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); await openCommandPaletteFromTrigger(); await page @@ -930,7 +1146,9 @@ describe("ChatView (full app): moving a thread to another computer", () => { await waitForServerConfigToApply(); await saveMacMini("disconnected"); await vi.waitFor(() => { - expect(readThreadMoveOffered(LOCAL_ENVIRONMENT_ID, undefined)).toBe(true); + expect( + readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), + ).toBe(true); }); await openCommandPaletteFromTrigger(); await page @@ -1152,12 +1370,25 @@ describe("ChatView (full app): moving a thread to another computer", () => { }); const thread = base.threads[0]!; const importedCount = thread.messages.length - 4; + // What Threadlines wrote for the agent on arrival, first in line here. + const arrival = { + ...createUserMessage({ + id: "msg-arrival" as MessageId, + text: "This thread moved from Mac mini to this computer, and your session was restarted for it.\n- Your goal is still on: ship the login fix. Carry on with it.", + offsetSeconds: importedCount * 3 - 0.5, + }), + afterMove: true as const, + }; const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, snapshot: withTestThread(base, { - messages: thread.messages.map((message, index) => - index < importedCount ? { ...message, imported: true as const } : message, - ), + messages: [ + ...thread.messages + .slice(0, importedCount) + .map((message) => ({ ...message, imported: true as const })), + arrival, + ...thread.messages.slice(importedCount), + ], movedFrom: { environmentId: FLEET_OFFLINE_ENVIRONMENT_ID, label: "Mac mini", @@ -1175,6 +1406,8 @@ describe("ChatView (full app): moving a thread to another computer", () => { fromLabel: "Mac mini", fromThreadId: "thread-on-mac-mini", movedAt: isoAt(importedCount * 3 - 1), + brought: ["its goal", "2 queued messages", "auto-fix for #212"], + left: [MOVED_IN_LEFT_SENTENCE], }, turnId: null, createdAt: isoAt(importedCount * 3 - 1), @@ -1198,6 +1431,28 @@ describe("ChatView (full app): moving a thread to another computer", () => { const top = (locator: typeof boundary) => locator.element().getBoundingClientRect().top; expect(top(lastImported)).toBeLessThan(top(boundary)); expect(top(boundary)).toBeLessThan(top(firstHere)); + + // Under it, what came along, then what didn't, with why. + await expect + .element(page.getByTestId("moved-in-brought")) + .toHaveTextContent("Its goal · 2 queued messages · auto-fix for #212"); + await expect + .element(page.getByTestId("moved-in-left")) + .toHaveTextContent(MOVED_IN_LEFT_SENTENCE); + + // The arrival message is Threadlines', a quiet row under its name + // folded to its first line, not the user's bubble. + const arrivalRow = await waitForElement( + () => document.querySelector('[data-after-move-message="msg-arrival"]'), + "The arrival message should show as Threadlines' row.", + ); + expect(arrivalRow.textContent).toContain("Threadlines·to the agent, about the move"); + expect(arrivalRow.textContent).toContain( + "This thread moved from Mac mini to this computer, and your session was restarted for it.", + ); + expect(arrivalRow.textContent).not.toContain("Your goal is still on"); + expect(arrivalRow.closest(".bg-secondary")).toBeNull(); + expect(top(boundary)).toBeLessThan(arrivalRow.getBoundingClientRect().top); } finally { await mounted.cleanup(); } @@ -1295,40 +1550,79 @@ describe("ChatView (full app): moving a thread to another computer", () => { ); const idleId = "thread-batch-idle" as ThreadId; const goalId = "thread-batch-goal" as ThreadId; + const chatId = "thread-batch-general-chat" as ThreadId; + const familyId = "thread-batch-family" as ThreadId; const queueManys: Array = []; const base = createSnapshotForTargetUser({ targetMessageId: "msg-user-move-batch" as MessageId, targetText: "move batch", }); - const snapshot = addThreadToSnapshot(addThreadToSnapshot(base, idleId), goalId); + const snapshot = withGeneralChats( + [idleId, goalId, chatId, familyId].reduce(addThreadToSnapshot, base), + [chatId], + ); + const titles = new Map([ + [idleId, "Idle docs pass"], + [goalId, "Goal thread"], + [chatId, "Best way to store passkeys"], + [familyId, "Family thread"], + ]); const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, snapshot: { ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === idleId - ? { ...thread, title: "Idle docs pass" } - : thread.id === goalId - ? { ...thread, title: "Goal thread" } - : thread, - ), + threads: snapshot.threads.map((thread) => ({ + ...thread, + title: titles.get(thread.id) ?? thread.title, + })), }, + // This computer moves threads with what they had going, General Chats included. configureFixture: (fixture) => withMoveCapabilities(fixture, { threadMove: true, threadMoveQueue: true, threadMoveBatch: true, + threadMoveState: true, }), resolveRpc: (body) => { if (body._tag === WS_METHODS.movesPreviewMany) { const threadIds = (body as unknown as { threadIds: ThreadId[] }).threadIds; + const working = [{ code: "turn" as const, words: "when this turn ends" }]; return { threads: threadIds.map((threadId) => threadId === THREAD_ID - ? { threadId, waitsFor: [{ code: "turn", words: "when this turn ends" }] } - : threadId === goalId - ? { threadId, refusal: "Has a goal set. Clear it first." } - : { threadId }, + ? { threadId, waitsFor: working } + : threadId === chatId + ? { + threadId, + waitsFor: working, + folder: { files: 14, bytes: 2_048 }, + targetLines: [ + { + environmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + projectName: "General chats", + }, + ], + } + : threadId === goalId + ? { + threadId, + brings: [{ words: "Its goal carries on there." }], + targetLines: [ + { + environmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + notes: [ + { + words: + "Its goal arrives paused: Claude on Mac mini can't keep its token budget. Resume runs it without one.", + }, + ], + }, + ], + } + : threadId === familyId + ? { threadId, refusal: "It started threads that are still working." } + : { threadId }, ), targets: [{ ...FLEET_MOVE_PREVIEW.targets[1]!, projectName: undefined }], }; @@ -1352,12 +1646,17 @@ describe("ChatView (full app): moving a thread to another computer", () => { const dialog = page.getByTestId("move-threads-dialog"); const list = dialog.getByTestId("move-threads-list"); await expect.element(list).toBeVisible(); - // The working thread leads, ticked; the idle one waits for the user. + // The working threads lead, ticked, the General Chats one with them; + // the idle ones wait for the user. const rows = Array.from( document.querySelectorAll('[data-testid^="move-threads-row-"]'), ).map((row) => row.dataset.testid); - expect(rows[0]).toBe(`move-threads-row-${THREAD_ID}`); - expect(rows).toHaveLength(3); + expect(rows.slice(0, 2)).toEqual([ + `move-threads-row-${THREAD_ID}`, + `move-threads-row-${chatId}`, + ]); + expect(rows).toHaveLength(5); + await expect.element(dialog.getByTestId(`move-threads-tick-${chatId}`)).toBeChecked(); await expect .element(dialog.getByTestId(`move-threads-words-${THREAD_ID}`)) .toHaveTextContent("Moves when the agent finishes"); @@ -1366,24 +1665,42 @@ describe("ChatView (full app): moving a thread to another computer", () => { .element(dialog.getByTestId(`move-threads-words-${idleId}`)) .toHaveTextContent("Moves now"); await expect.element(dialog.getByTestId(`move-threads-tick-${idleId}`)).not.toBeChecked(); - // One that can't move is listed, greyed out, with why. + // A thread with a goal moves, and says what comes along. await expect .element(dialog.getByTestId(`move-threads-words-${goalId}`)) - .toHaveTextContent("Has a goal set. Clear it first."); - await expect.element(dialog.getByTestId(`move-threads-tick-${goalId}`)).toBeDisabled(); + .toHaveTextContent("Moves now"); + await expect + .element(dialog.getByTestId(`move-threads-brings-${goalId}`)) + .toHaveTextContent("Its goal carries on there."); + // What won't work there as it did, for the agent it moves with. + await expect + .element(dialog.getByTestId(`move-threads-note-${goalId}`)) + .toHaveTextContent( + "Its goal arrives paused: Claude on Mac mini can't keep its token budget. Resume runs it without one.", + ); + await expect.element(dialog.getByTestId(`move-threads-tick-${goalId}`)).toBeEnabled(); + // A General Chats thread says where it lands, with its files. + await expect + .element(dialog.getByTestId(`move-threads-landing-${chatId}`)) + .toHaveTextContent("Lands in General chats on Mac mini · 14 files"); + // One that can't move is listed, greyed out, with why. + await expect + .element(dialog.getByTestId(`move-threads-words-${familyId}`)) + .toHaveTextContent("It started threads that are still working."); + await expect.element(dialog.getByTestId(`move-threads-tick-${familyId}`)).toBeDisabled(); await expect .element(dialog.getByTestId("move-threads-confirm")) - .toHaveTextContent("Move 1 thread"); + .toHaveTextContent("Move 2 threads"); - await dialog.getByTestId(`move-threads-tick-${idleId}`).click(); + await dialog.getByTestId(`move-threads-tick-${goalId}`).click(); await expect .element(dialog.getByTestId("move-threads-confirm")) - .toHaveTextContent("Move 2 threads"); + .toHaveTextContent("Move 3 threads"); await dialog.getByTestId("move-threads-confirm").click(); await expect.element(page.getByTestId("move-threads-dialog")).not.toBeInTheDocument(); expect(queueManys).toEqual([ expect.objectContaining({ - threadIds: [THREAD_ID, idleId], + threadIds: [THREAD_ID, chatId, goalId], targetEnvironmentId: FLEET_OFFLINE_ENVIRONMENT_ID, mode: "when-done", }), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d060fea2b..cc25471b2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -6507,8 +6507,11 @@ export default function ChatView(props: ChatViewProps) { // The box holds one message for one agent. In a room, only the messages // for the first one's agent come back; the rest stay queued for theirs. // What an agent queued (a hand-off, a reply, another thread's request or - // answer) is never the user's to edit. - const usersOwn = followUps.filter((followUp) => !isAgentOrigin(followUp)); + // answer), or Threadlines wrote for the agent after a move, is never the + // user's to edit. + const usersOwn = followUps.filter( + (followUp) => !isAgentOrigin(followUp) && followUp.afterMove !== true, + ); const firstAgentId = usersOwn[0]?.participantId ?? null; const returning = isRoom(activeThread) ? usersOwn.filter((followUp) => (followUp.participantId ?? null) === firstAgentId) diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 22f7a194e..bfdd5cb04 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -616,8 +616,13 @@ export function OpenCommandPaletteDialog() { // Clearing this computer (Part 3c): several of its threads to a linked one. const moveThreadsOffered = useMoveThreadsOffered(primaryEnvironmentId, null); const activeThreadMoveOffered = useThreadMoveOffered( - activeThread?.environmentId ?? null, - activeThread ? threadMoveStatus(activeThread) : undefined, + activeThread + ? { + environmentId: activeThread.environmentId, + projectId: activeThread.projectId, + moveStatus: threadMoveStatus(activeThread), + } + : null, ); // The open thread's own actions are its menu's (useThreadMenu); the inbox // says whether it offers Wrap up or Reopen. This mounts only while open. diff --git a/apps/web/src/components/MoveThreadsDialogContent.tsx b/apps/web/src/components/MoveThreadsDialogContent.tsx index 0056b654c..fcdaef811 100644 --- a/apps/web/src/components/MoveThreadsDialogContent.tsx +++ b/apps/web/src/components/MoveThreadsDialogContent.tsx @@ -1,8 +1,8 @@ /** * The body of "Move threads" (MoveThreadsDialog.tsx): the computer they go * to, the computer's open threads (working ones first and ticked, idle ones - * unticked, ones that can't move greyed out with why), one choice for the - * working ones, and "Move N threads". Its own chunk, loaded the first time + * unticked, ones that can't move greyed out with why, each with what comes + * along), one choice for the working ones, and "Move N threads". Its own chunk, loaded the first time * the host shows a request. */ import type { @@ -16,7 +16,10 @@ import type { import { useEffect, useMemo, useState } from "react"; import { describeComputerLinkFailure } from "../environments/links/computerLinks"; -import { requireThreadMovesClient } from "../environments/links/threadMoves"; +import { + requireThreadMovesClient, + useThreadMoveStateSupported, +} from "../environments/links/threadMoves"; import { useInboxThreads } from "../hooks/useInboxThreads"; import { rememberMoveBatch } from "../moveBatchProgress"; import { cn } from "../lib/utils"; @@ -55,11 +58,18 @@ const plural = (count: number, one: string, many: string) => `${count} ${count = export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDialogRequest }) { const { sourceEnvironmentId } = request; const sourceLabel = useComputerLabel()(sourceEnvironmentId, sourceEnvironmentId); - const { entries } = useInboxThreads(); + const { entries, generalChatEntries } = useInboxThreads(); + // General Chats threads go too where the computer moves them (Part 3e). + const movesGeneralChats = useThreadMoveStateSupported(sourceEnvironmentId); // The list as it was when the dialog opened: rows don't jump while the // user ticks them, even as threads start and finish. const [candidates] = useState(() => - listMoveCandidates(entries, sourceEnvironmentId, isSidebarThreadRunning), + listMoveCandidates( + entries, + movesGeneralChats ? generalChatEntries : [], + sourceEnvironmentId, + isSidebarThreadRunning, + ), ); const [previewState, setPreviewState] = useState({ status: "loading" }); const [targetId, setTargetId] = useState(null); @@ -130,12 +140,12 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial { candidate, preview: threadPreview, - words: describeMoveCandidate(threadPreview, targetId), + words: describeMoveCandidate(threadPreview, targetId, target?.label), }, ] : []; }), - [candidates, previewById, targetId], + [candidates, previewById, targetId, target?.label], ); // What goes: the ticked rows that can go to the computer picked now. const chosen = rows.filter( @@ -196,8 +206,8 @@ export function MoveThreadsDialogContent({ request }: { request: MoveThreadsDial Move threads - Threads on {sourceLabel} go with their messages and code changes. Your copies here stay, - read-only. + Threads on {sourceLabel} go with their messages, and code changes or a chat's files. Your + copies here stay, read-only. @@ -374,6 +384,14 @@ function CandidateList({ > {words.words} + {words.landing !== undefined ? ( + + {words.landing} + + ) : null} {words.session !== undefined ? ( ) : null} + {(words.brings ?? []).map((line) => ( + + {line} + + ))} + {(words.notes ?? []).map((line) => ( + + {line} + + ))} diff --git a/apps/web/src/components/ThreadMoveDialogContent.tsx b/apps/web/src/components/ThreadMoveDialogContent.tsx index ba182a43d..e642121d1 100644 --- a/apps/web/src/components/ThreadMoveDialogContent.tsx +++ b/apps/web/src/components/ThreadMoveDialogContent.tsx @@ -27,6 +27,7 @@ import { import { cn } from "../lib/utils"; import { selectSidebarThreadSummaryByRef, useStore } from "../store"; import { + describeThreadMoveLanding, describeThreadMoveSession, describeThreadMoveWaits, formatThreadMoveChanges, @@ -36,6 +37,7 @@ import { threadMoveAgentKey, threadMoveAgentSelection, threadMoveSessionOutcome, + threadMoveNotesFor, threadMoveStopNowRefusal, type ThreadMoveAgentChoice, } from "../threadMove"; @@ -144,6 +146,12 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread const unreachable = queues && target?.unreachable === true; const agentSelection: ModelSelection | null = target !== null && agent !== null ? threadMoveAgentSelection(target, agent) : null; + // A General Chats thread: its folder goes, with no branch or staged changes. + const folder = preview?.folder; + // What comes along, then what won't work there as it did, for the agent picked. + const pickedInstanceId = unreachable ? null : (agentSelection?.instanceId ?? null); + const brings = threadMoveNotesFor(preview?.brings, pickedInstanceId); + const notes = threadMoveNotesFor(target?.notes, pickedInstanceId); const canMove = preview !== null && preview.refusal === undefined && @@ -180,9 +188,9 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread Move to another computer - {title - ? `“${title}” goes with its messages and its code changes.` - : "The thread goes with its messages and its code changes."} + {`${title ? `“${title}”` : "The thread"} goes with its messages and its ${ + folder !== undefined ? "files" : "code changes" + }.`} @@ -254,12 +262,13 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread className="surface-group space-y-0.5 px-3.5 py-2.5" data-testid="thread-move-preview" > -

- {target.projectName - ? `Lands in ${target.projectName} on ${target.label}` - : `Lands on ${target.label}`} +

+ {describeThreadMoveLanding(target, folder)}

- {preview.changes ? ( + {folder === undefined && preview.changes ? (

) : null} -

- Staged changes arrive as unstaged changes. -

+ {folder === undefined ? ( +

+ Staged changes arrive as unstaged changes. +

+ ) : null}

Your copy here stays, read-only.

@@ -305,6 +316,28 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread ) : null} )} + {brings.length > 0 || notes.length > 0 ? ( +
+ {brings.map((line) => ( +

+ {line} +

+ ))} + {notes.map((line) => ( +

+ {line} +

+ ))} +
+ ) : null} {working ? ( {paused ? "Paused" : "Queued"} @@ -157,14 +165,14 @@ function QueuedFollowUpLine({ {describeQueuedFollowUp(followUp, attachmentOnlyPrompt)} {byAgent && !fromOutside ? null : ( <> - {fromOutside ? null : ( + {notUsers ? null : (