diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 489fcc721..b849aa012 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -144,7 +144,7 @@ Linking is two-way, with a permission for each direction: "'s agents can star With a link allowed, an agent can start a thread on the other computer in that computer's copy of the project, read it and message it, and its reply comes back. A computer you only open from this app (Settings › Connections › Computers you use from here) is not a link: you see its threads here, but agents can't work across. This app's sign-in to it renews whenever they connect and ends after 90 days without one, or when that computer removes it. Fleet's All computers page and its own page then say the sign-in ended and offer to connect again with a new code; its threads stay on it. -To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, 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.`, +To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, its pull requests come along with auto-fix and auto-merge off (a notice there says what was on, with Turn on), and its plans come along, the waiting one with Implement. Until you send the moved thread a message there, its agent can't use other threads, rooms or schedules. A General Chats thread moves with every file in its folder, up to 100 MB. The dialog says what comes along and what won't work there; the "Moved here" line on the other computer says what arrived and what didn't. If a move doesn't happen, the thread gets back here what the move stopped: its goal and its check-backs, and its queued messages go. A 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/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index e427f6fdf..2776a8019 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -1047,7 +1047,21 @@ describe("LinkMoves, what a thread had going (Part 3e)", () => { 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 }); + // The pull request comes along with its switch off: only the user here + // turns it on, from the offer the thread keeps. assert.deepEqual(command.pullRequests, { + autoFix: false, + autoMerge: null, + linked: [ + { + number: 212, + url: "https://example.com/repo/pull/212", + autoFix: false, + autoMerge: null, + }, + ], + }); + assert.deepEqual(command.movedFrom.pullRequestSwitches, { autoFix: true, autoMerge: null, linked: [ @@ -1067,12 +1081,16 @@ describe("LinkMoves, what a thread had going (Part 3e)", () => { assert.include(message, "Look at CI on #212"); assert.deepEqual(command.arrival?.brought, [ "its goal", - "auto-fix for #212", + "pull request #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."); + assert.include( + command.arrival?.left.join("\n"), + "Auto-fix was on for this thread's pull request and #212 on Windows PC. It's off here until you turn it on.", + ); // One send: the arrival message, by the move's own command id. assert.deepEqual( sends(dispatched).map((entry) => @@ -1180,6 +1198,8 @@ describe("LinkMoves, what a thread had going (Part 3e)", () => { 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.", ); + // Turning it on wouldn't reach the pull request: nothing is offered. + assert.isUndefined(command.movedFrom.pullRequestSwitches); }).pipe( Effect.provide( testLayer(repos, dispatched, "allowed", () => false, [], { diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 2e499656c..cfe85bb91 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -56,6 +56,7 @@ import { type ProviderInstanceId, type ProviderInteractionMode, type PullRequestMergeMethod, + type ThreadMovedFrom, type RuntimeMode, PEER_MOVE_CHUNK_MAX_BYTES, PEER_MOVE_STATE_MAX_BYTES, @@ -88,6 +89,10 @@ 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 { + movedPullRequestSwitchesWords, + pullRequestSwitchesWords, +} from "@threadlines/shared/threadMoveProjection"; import { arrivalMessageText } from "../moves/arrivalMessage.ts"; import { MOVE_MAX_BYTES } from "../moves/moveExport.ts"; import { derivedUuid } from "../orchestration/childRequestIds.ts"; @@ -1829,7 +1834,7 @@ const make = Effect.gen(function* () { ? device.value.label : row.manifest.source.environmentLabel; const scratch = isScratchMoveManifest(row.manifest); - const state = yield* importedState({ + const { pullRequestSwitches, ...state } = yield* importedState({ row, root: land.root, instanceId: agent.selection.instanceId, @@ -1857,6 +1862,7 @@ const make = Effect.gen(function* () { label: fromLabel, threadId: row.manifest.source.threadId, movedAt: now, + ...(pullRequestSwitches !== undefined ? { pullRequestSwitches } : {}), }, messages, activities, @@ -1901,7 +1907,7 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const { row, now } = input; const state = row.manifest.thread.state; - if (state === undefined) return {}; + if (state === undefined) return { pullRequestSwitches: undefined }; const key = row.transferKey; const capabilities = yield* providers .getCapabilities(input.instanceId) @@ -1969,7 +1975,11 @@ const make = Effect.gen(function* () { } } - // (c) Pull request switches. + // (c) Pull requests: the links come along, every switch off. A switch + // acts with this computer's GitHub sign-in, so only the user here turns + // one on; the "Moved here" line and the thread's notice offer what was + // on there (movedFrom.pullRequestSwitches). + let pullRequestSwitches: ThreadMovedFrom["pullRequestSwitches"]; let pullRequests: | { readonly autoFix: boolean; @@ -1996,33 +2006,37 @@ const make = Effect.gen(function* () { : 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, + autoFix: false, + autoMerge: null, + linked: carriedSwitches.linked.map((entry) => ({ + number: entry.number, + url: entry.url, + autoFix: false, + autoMerge: null, + })), }; + if (numbers.length > 0) brought.push(which); + const wasOn = movedPullRequestSwitchesWords(carriedSwitches, input.fromLabel); if (off !== null) { - left.push(off); - } else { + if (pullRequestSwitchesWords(carriedSwitches) !== null) left.push(off); + } else if (wasOn !== null) { + pullRequestSwitches = { + autoFix: carriedSwitches.autoFix, + autoMerge: carriedSwitches.autoMerge, + linked: carriedSwitches.linked + .filter((entry) => entry.autoFix || entry.autoMerge !== null) + .map((entry) => ({ + number: entry.number, + url: entry.url, + autoFix: entry.autoFix, + autoMerge: entry.autoMerge, + })), + }; + left.push(wasOn); 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.", - ); + left.push("GitHub isn't signed in on this computer. Sign in before you turn them on."); } } } @@ -2098,6 +2112,7 @@ const make = Effect.gen(function* () { ...(pullRequests !== undefined ? { pullRequests } : {}), ...(queuedFollowUps.length > 0 ? { queuedFollowUps } : {}), ...(proposedPlans.length > 0 ? { proposedPlans } : {}), + ...(pullRequestSwitches !== undefined ? { pullRequestSwitches } : {}), arrival: { ...(text !== null ? { message: { messageId: arrivalMessageId(row), text } } : {}), brought, diff --git a/apps/server/src/mcp/scheduleToolHandlers.ts b/apps/server/src/mcp/scheduleToolHandlers.ts index ae4d47c8e..4812e4f4f 100644 --- a/apps/server/src/mcp/scheduleToolHandlers.ts +++ b/apps/server/src/mcp/scheduleToolHandlers.ts @@ -24,6 +24,7 @@ import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; import { derivedUuid } from "../orchestration/childRequestIds.ts"; +import { isLinkFenced, linkFenceRefusal } from "../orchestration/linkFence.ts"; import { providerModelReasoning, reasoningLevel, @@ -135,8 +136,13 @@ export function makeScheduleToolHandlers(deps: ScheduleToolDeps) { return { refusal: { outcome: "refused" as const, detail: GONE } }; } // The fence: its runtime has no Threadlines tools; this guards a stale credential. - if ((thread.remoteOrigin ?? null) !== null) { - return { refusal: { outcome: "not_allowed" as const, detail: REMOTE_ORIGIN_REFUSAL } }; + if (isLinkFenced(thread)) { + return { + refusal: { + outcome: "not_allowed" as const, + detail: linkFenceRefusal(thread, "schedule tools"), + }, + }; } return { mode, thread, service }; }); @@ -372,8 +378,14 @@ export function makeScheduleToolHandlers(deps: ScheduleToolDeps) { return { outcome: "not_a_run" as const, detail: NO_SCHEDULES }; } const thread = yield* deps.readThread(scope.threadId); - if (thread === undefined || (thread.remoteOrigin ?? null) !== null) { - return { outcome: "not_allowed" as const, detail: REMOTE_ORIGIN_REFUSAL }; + if (thread === undefined || isLinkFenced(thread)) { + return { + outcome: "not_allowed" as const, + detail: + thread === undefined + ? REMOTE_ORIGIN_REFUSAL + : linkFenceRefusal(thread, "schedule tools"), + }; } const latched = yield* latchCallerTurn(deps.readThread, scope); if ("gone" in latched) return { outcome: "not_a_run" as const, detail: GONE }; diff --git a/apps/server/src/mcp/threadToolHandlers.test.ts b/apps/server/src/mcp/threadToolHandlers.test.ts index 34685c635..4942e632f 100644 --- a/apps/server/src/mcp/threadToolHandlers.test.ts +++ b/apps/server/src/mcp/threadToolHandlers.test.ts @@ -1457,6 +1457,37 @@ describe("thread tools across linked computers", () => { expect(tools.dispatched).toEqual([]); }), ); + + it.effect( + "gives a thread that moved here no thread tools until the user here takes it over", + () => + Effect.gen(function* () { + const movedFrom = { + environmentId: EnvironmentId.make("env-windows"), + label: "Windows PC", + threadId: ThreadId.make("windows-thread"), + movedAt: "2026-01-01T00:00:00.000Z", + }; + const fenced = yield* makeTools({ + links: fakeLinks(), + caller: makeThread({ movedFrom: { ...movedFrom, fenced: true } }), + }); + const read = yield* fenced.handlers.thread_read(mainCaller(), { threadId: CHILD }); + const listed = yield* fenced.handlers.thread_list(mainCaller(), { scope: "project" }); + expect(read.outcome).toBe("not_allowed"); + expect(read.detail).toContain("moved here from Windows PC"); + expect(listed.outcome).toBe("not_allowed"); + // Once it has: the same thread reads as any other. + const lifted = yield* makeTools({ + links: fakeLinks(), + caller: makeThread({ movedFrom }), + others: [makeChild()], + }); + expect( + (yield* lifted.handlers.thread_read(mainCaller(), { threadId: CHILD })).outcome, + ).toBe("ok"); + }), + ); }); describe("thread_move", () => { diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index bc572a18f..f790c3792 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -67,6 +67,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { childRequestCommandId, derivedUuid } from "../orchestration/childRequestIds.ts"; +import { isLinkFenced, linkFenceRefusal } from "../orchestration/linkFence.ts"; import { checkoutMoveRefusal, childHasLiveWork, @@ -479,11 +480,20 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { if (thread === undefined) { return { refusal: { outcome: "refused" as const, detail: GONE } }; } - // A thread another computer's agent started here never gets these + // A thread another computer's agent started here never gets these, nor + // one that moved here until the user here takes it over // (docs/design/fleet.md, "Fence"); its runtime has no thread tools, so - // this only guards a stale credential. - if ((thread.remoteOrigin ?? null) !== null) { - return { refusal: { outcome: "not_allowed" as const, detail: REMOTE_ORIGIN_REFUSAL } }; + // this guards a stale credential, and a runtime from before the move. + if (isLinkFenced(thread)) { + return { + refusal: { + outcome: "not_allowed" as const, + detail: + (thread.remoteOrigin ?? null) !== null + ? REMOTE_ORIGIN_REFUSAL + : linkFenceRefusal(thread, "thread tools"), + }, + }; } return { mode, thread }; }); diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index 069993917..8c9a596ef 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -357,7 +357,7 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { goalHoldsTurn: true, }); expect(preview.notes).toEqual([ - { words: "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in." }, + { words: "GitHub isn't signed in on Mac mini. Sign in there before you turn auto-fix on." }, { words: "Its goal arrives paused: Claude on Mac mini can't keep its token budget. Resume runs it without one.", @@ -390,7 +390,7 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { }); expect(carryBringsWords(threadMoveCarry(view, thread))).toEqual([ "Its goal arrives paused.", - "Auto-fix keeps watching pull request #212 from there.", + "Auto-fix for pull request #212 arrives off, for you to turn on there.", "1 queued message is sent there.", ]); }); @@ -446,7 +446,9 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { { environmentId: MAC_MINI, notes: [ - { words: "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in." }, + { + words: "GitHub isn't signed in on Mac mini. Sign in there before you turn auto-fix on.", + }, { 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 026d4261c..f71910c34 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -277,7 +277,7 @@ export function targetNotesOf( 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.`, + words: `GitHub isn't signed in on ${peer.label}. Sign in there before you turn auto-fix on.`, }); } for (const agent of peer.agents) { diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index ce5eba171..94f1ef392 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2646,6 +2646,106 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { }), ); + it.effect( + "keeps a moved thread's fence and its switch offer through a restart, until the user here ends each", + () => + Effect.gen(function* () { + const engine = yield* OrchestrationEngineService; + const snapshots = yield* ProjectionSnapshotQuery; + const createdAt = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-moved-fenced"); + const projectId = ProjectId.make("project-moved-fenced"); + const pullRequest = { number: 212, url: "https://github.com/acme/w/pull/212" }; + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.make("cmd-moved-fenced-project"), + projectId, + title: "Moved Fenced", + workspaceRoot: "/tmp/project-moved-fenced", + createdAt, + }); + yield* engine.dispatch({ + type: "thread.import", + commandId: CommandId.make("cmd-moved-fenced-import"), + threadId, + projectId, + title: "Fix the flaky test", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + movedFrom: { + environmentId: EnvironmentId.make("environment-pc"), + label: "Windows PC", + threadId: ThreadId.make("thread-there"), + movedAt: createdAt, + pullRequestSwitches: { + autoFix: false, + autoMerge: null, + linked: [{ ...pullRequest, autoFix: true, autoMerge: null }], + }, + }, + messages: [], + activities: [], + pullRequests: { + autoFix: false, + autoMerge: null, + linked: [{ ...pullRequest, autoFix: false, autoMerge: null }], + }, + createdAt, + }); + // What a restart reads: the command model, the shell and the detail. + const movedFromNow = () => + Effect.gen(function* () { + const model = yield* snapshots.getCommandReadModel(); + const shell = Option.getOrThrow(yield* snapshots.getThreadShellById(threadId)); + const detail = Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)); + assert.deepEqual(shell.movedFrom, detail.movedFrom); + return { + command: model.threads.find((thread) => thread.id === threadId)?.movedFrom, + detail: detail.movedFrom, + }; + }); + const arrived = yield* movedFromNow(); + assert.equal(arrived.command?.fenced, true); + assert.equal(arrived.detail?.fenced, true); + assert.equal(arrived.detail?.pullRequestSwitches?.linked[0]?.autoFix, true); + + // The user here turns the switch on: the offer goes, the fence stays. + yield* engine.dispatch({ + type: "thread.pull-request-automation.set", + commandId: CommandId.make("cmd-moved-fenced-switch"), + threadId, + pullRequestNumber: pullRequest.number, + autoFix: true, + }); + const switched = yield* movedFromNow(); + assert.isUndefined(switched.detail?.pullRequestSwitches); + assert.equal(switched.command?.fenced, true); + + // The user here sends it a message: the fence lifts, for good. + yield* engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-moved-fenced-turn"), + threadId, + message: { + messageId: MessageId.make("message-moved-fenced"), + role: "user", + text: "Carry on", + attachments: [], + }, + runtimeMode: "approval-required", + interactionMode: "default", + createdAt, + }); + const lifted = yield* movedFromNow(); + assert.isUndefined(lifted.command?.fenced); + assert.isUndefined(lifted.detail?.fenced); + assert.equal(lifted.detail?.label, "Windows PC"); + }), + ); + it.effect( "keeps what a move owes back, and the message it wrote for the agent, in every read", () => diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 8c9f32793..142322932 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -42,7 +42,7 @@ import { } from "@threadlines/shared/pendingRequests"; import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts"; -import { nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; +import { movedFromAfter, nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; import { withQueuedFollowUp } from "@threadlines/shared/queuedFollowUps"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts"; @@ -733,6 +733,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti existingRow.value.linkedPullRequests, { pullRequestNumber, autoFix, autoMerge }, ), + ...(event.payload.clearsMovedSwitches === true + ? { + movedFrom: movedFromAfter(existingRow.value.movedFrom, { + clearsSwitches: true, + }), + } + : {}), updatedAt: event.payload.updatedAt, }); return; @@ -741,6 +748,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...existingRow.value, ...(autoFix === undefined ? {} : { pullRequestAutoFix: autoFix ? 1 : 0 }), ...(autoMerge === undefined ? {} : { pullRequestAutoMerge: autoMerge }), + ...(event.payload.clearsMovedSwitches === true + ? { + movedFrom: movedFromAfter(existingRow.value.movedFrom, { clearsSwitches: true }), + } + : {}), updatedAt: event.payload.updatedAt, }); return; @@ -1032,6 +1044,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionThreadRepository.upsert({ ...existingRow.value, participants, + // See the in-memory projector: the user here took it over. + ...(event.payload.liftsMoveFence === true + ? { movedFrom: movedFromAfter(existingRow.value.movedFrom, { liftsFence: true }) } + : {}), sentModels: recordTurnModel( { ...existingRow.value, participants }, participantId, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 8e634eccd..33101e5c3 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -3347,8 +3347,16 @@ describe("ProviderCommandReactor", () => { runtimeMode: "full-access", createdAt: now, }); - const settleReady = (id: string) => - dispatch({ + // The runtime goes ready once its turn is done. The reactor records a + // sent turn as running a moment after the send; wait for that first, or + // its late write would land on top of this ready and the next turn would + // read as arriving mid-turn. + const settleReady = async (id: string) => { + await waitFor(async () => { + const session = await projectedSession(harness, threadId); + return session?.status === "running" && session.activeTurnId === asTurnId("turn-1"); + }); + await dispatch({ type: "thread.session.set", commandId: CommandId.make(`cmd-ready-${id}`), threadId, @@ -3363,6 +3371,7 @@ describe("ProviderCommandReactor", () => { }, createdAt: now, }); + }; // Before the thread is a room: no room tools, only the app guide. await startTurn("before-room"); @@ -3398,6 +3407,105 @@ describe("ProviderCommandReactor", () => { expect(harness.startSession.mock.calls.length).toBe(2); }); + it("a thread that moved here works with no Threadlines tools until the user here sends it a message", async () => { + const harness = await createHarness({ + serverSettings: { agentInvites: "off", agentThreads: "off" }, + }); + const now = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-moved-here"); + const dispatch = (command: Parameters[0]) => + Effect.runPromise(harness.engine.dispatch(command)); + // The runtime goes ready once its turn is done. The reactor records a + // sent turn as running a moment after the send; wait for that first, or + // its late write would land on top of this ready and the next turn would + // read as arriving mid-turn. + const settleReady = async (id: string) => { + await waitFor(async () => { + const session = await projectedSession(harness, threadId); + return session?.status === "running" && session.activeTurnId === asTurnId("turn-1"); + }); + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-ready-${id}`), + threadId, + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }); + }; + await dispatch({ + type: "thread.import", + commandId: CommandId.make("cmd-import"), + threadId, + projectId: asProjectId("project-1"), + title: "Fix the flaky test", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + movedFrom: { + environmentId: EnvironmentId.make("env-windows"), + label: "Windows PC", + threadId: ThreadId.make("windows-thread"), + movedAt: now, + }, + messages: [], + activities: [], + queuedFollowUps: [ + { + messageId: asMessageId("queued-there"), + text: "then run the suite", + attachments: [], + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: now, + }, + ], + createdAt: now, + }); + + // The move's own kick sends what the user queued there: still fenced. + await dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-kick"), + threadId, + messageId: asMessageId("queued-there"), + createdAt: now, + }); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.startSession.mock.calls[0]?.[1]).not.toHaveProperty("roomTools"); + expect(harness.startSession.mock.calls[0]?.[1]).not.toHaveProperty("guideTools"); + + // The user here takes it over: the runtime restarts with resume, with the guide. + await settleReady("1"); + await dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-user-here"), + threadId, + message: { messageId: asMessageId("user-here"), role: "user", text: "go", attachments: [] }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: now, + }); + await waitFor( + () => harness.sendTurn.mock.calls.length === 2 || harness.steerTurn.mock.calls.length > 0, + ); + expect(harness.steerTurn.mock.calls.length, "steered instead of a new turn").toBe(0); + expect(harness.startSession.mock.calls.length).toBe(2); + expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ + guideTools: true, + resumeCursor: { opaque: "resume-1" }, + }); + }); + it("starts an agent outside work reached fresh for a person's next message, then clears its mark", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index c052aeeb5..aac600a6f 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -160,6 +160,7 @@ import { handOffReplyText } from "../agentRequestDecisions.ts"; import { isCancelledReport } from "../childThreadDecisions.ts"; import { NO_BACKGROUND_TASKS } from "../sessionBackgroundTasks.ts"; import { isRestorePaid } from "../threadMoveDecisions.ts"; +import { isLinkFenced } from "../linkFence.ts"; import { SideAnswerStartError } from "../Errors.ts"; const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError); const isProviderAdapterValidationError = Schema.is(ProviderAdapterValidationError); @@ -651,6 +652,15 @@ const make = Effect.gen(function* () { */ const threadsMovedAwayFromSession = new Set(); + /** + * Sessions started behind the link fence (linkFence.ts), which got no + * Threadlines tools, not even the guide. A moved thread's fence lifts with + * the user's message here, and its next start restarts the session (with + * resume) to pick them up. In memory only: after a server restart every + * session starts again with the thread as it is then. + */ + const sessionsStartedFenced = new Set(); + /** * Sessions that came up without their conversation (the provider couldn't * reopen it), keyed by participant session key. Whichever path restarted @@ -1425,10 +1435,11 @@ const make = Effect.gen(function* () { // started here gets none of them: it must not reach other threads here // (docs/design/fleet.md, "Fence"). Nor does one an outside agent started: // through its tools the agent could reach past what it was allowed - // (docs/design/outside-agents.md, "Fence"). + // (docs/design/outside-agents.md, "Fence"). Nor does one that moved here + // with work from the other computer, until the user here sends it a + // message (Part 3e). const scheduledRunTools = (thread.scheduledRun ?? null) !== null && participantId === null; - const fencedOff = - (thread.remoteOrigin ?? null) !== null || (thread.outsideOrigin ?? null) !== null; + const fencedOff = isLinkFenced(thread) || (thread.outsideOrigin ?? null) !== null; const roomToolsWanted = !fencedOff && (hasAgentRecords(thread) || @@ -1439,6 +1450,10 @@ const make = Effect.gen(function* () { // it can't start threads, its agent can say where that is turned on // (docs/design/app-guide.md, "The tool"). const guideTools = !fencedOff && !roomToolsWanted; + const noteSessionFence = Effect.sync(() => { + if (fencedOff) sessionsStartedFenced.add(sessionKey); + else sessionsStartedFenced.delete(sessionKey); + }); const desiredRuntimeMode = early?.runtimeMode ?? thread.runtimeMode; const requestedModelSelection = options?.modelSelection; @@ -1661,6 +1676,7 @@ const make = Effect.gen(function* () { }).pipe( Effect.andThen( providerService.startSession(sessionKey, sessionStartInput(input)).pipe( + Effect.tap(() => noteSessionFence), withMetrics({ timer: providerSessionStartDuration, attributes: { provider: preferredProvider, startKind }, @@ -1794,6 +1810,7 @@ const make = Effect.gen(function* () { (activeSession === undefined || (yield* providerService.isEarlySession(sessionKey))) ) { yield* providerService.startEarlySession(sessionKey, sessionStartInput()); + yield* noteSessionFence; } return { sessionThreadId: sessionKey, nativeForkApplied: false }; } @@ -1932,10 +1949,13 @@ const make = Effect.gen(function* () { : Effect.void; // A runtime started before its thread became a room, or before invites - // were turned on, has no room tools. It gets them by restarting with - // resume, once; an adapter that could not attach them reports false, - // and restarting again would not help. - const roomToolsMissing = roomToolsWanted && activeSession?.roomTools === undefined; + // were turned on, or behind a fence that has lifted since, has no room + // tools (or no guide). It gets them by restarting with resume, once; an + // adapter that could not attach them reports false, and restarting + // again would not help. + const roomToolsMissing = + (roomToolsWanted && activeSession?.roomTools === undefined) || + (!fencedOff && activeSession !== undefined && sessionsStartedFenced.has(sessionKey)); // An agent outside text reached sheds it by starting fresh for a turn // that isn't from outside: the old runtime, and whatever it left // running, loses its token. diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts index cedead440..069cb4b91 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts @@ -604,6 +604,8 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher modelSelection: input.thread.modelSelection, runtimeMode: input.thread.runtimeMode, interactionMode: input.thread.interactionMode, + // Its message is ours, not the user's: a moved thread stays fenced. + keepsMoveFence: true, createdAt, }) .pipe( diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 6627c3454..26c27dba4 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -1357,21 +1357,23 @@ describe("a move carries what its thread had going (Part 3e)", () => { }), ); const planned = Array.isArray(events) ? events : [events]; + // The pull request is linked, its switches stay off: the peer can't + // turn one on here, whatever its command says. 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", ]); + // It arrives fenced. + expect(planned[0]?.payload).toMatchObject({ movedFrom: { fenced: true } }); 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" } }, + { imported: true, followUp: { messageId: "q-there", imported: true } }, ]); expect(planned.at(-1)?.payload).toMatchObject({ activity: { @@ -1423,6 +1425,155 @@ describe("a move carries what its thread had going (Part 3e)", () => { }); }); +describe("what a moved thread is trusted with (Part 3e, security changes)", () => { + const ARRIVED = ThreadId.make("thread-arrived-fenced"); + const PULL_REQUEST = { number: 212, url: "https://github.com/acme/w/pull/212" }; + const imported = async () => + ( + 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-fenced", + movedFrom: { + ...MAC_MINI, + threadId: THREAD, + movedAt: now, + pullRequestSwitches: { + autoFix: false, + autoMerge: null, + linked: [{ ...PULL_REQUEST, autoFix: true, autoMerge: "squash" }], + }, + }, + messages: [], + activities: [], + pullRequests: { + autoFix: false, + autoMerge: null, + linked: [{ ...PULL_REQUEST, autoFix: false, autoMerge: null }], + }, + queuedFollowUps: [ + { + messageId: MessageId.make("q-there"), + text: "and then this", + attachments: [], + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + }, + ], + arrival: { + message: { messageId: MessageId.make("m-arrival"), text: "This thread moved." }, + brought: ["pull request #212"], + left: [], + }, + createdAt: now, + }) + ).model; + const userTurn = (extra: Record = {}): OrchestrationCommand => + ({ + type: "thread.turn.start", + commandId: nextCommandId(), + threadId: ARRIVED, + message: { + messageId: MessageId.make(`m-${sequence}`), + role: "user", + text: "Carry on", + attachments: [], + }, + runtimeMode: "auto", + interactionMode: "default", + createdAt: now, + ...extra, + }) as OrchestrationCommand; + const sendQueued = (messageId: string): OrchestrationCommand => ({ + type: "thread.follow-up.send-queued", + commandId: nextCommandId(), + threadId: ARRIVED, + messageId: MessageId.make(messageId), + createdAt: now, + }); + + it("an imported pull request switch arrives off, and the user's own turn-on works and ends the offer", async () => { + let model = await imported(); + const arrived = threadOf(model, ARRIVED); + expect(arrived.linkedPullRequests).toMatchObject([ + { number: 212, autoFix: false, autoMerge: null }, + ]); + expect(arrived.movedFrom?.pullRequestSwitches?.linked).toMatchObject([ + { number: 212, autoFix: true, autoMerge: "squash" }, + ]); + + let refusal: string | null; + ({ model, refusal } = await apply(model, { + type: "thread.pull-request-automation.set", + commandId: nextCommandId(), + threadId: ARRIVED, + pullRequestNumber: 212, + autoFix: true, + autoMerge: "squash", + })); + expect(refusal).toBeNull(); + const turnedOn = threadOf(model, ARRIVED); + expect(turnedOn.linkedPullRequests).toMatchObject([ + { number: 212, autoFix: true, autoMerge: "squash" }, + ]); + expect(turnedOn.movedFrom?.pullRequestSwitches).toBeUndefined(); + expect(turnedOn.movedFrom?.fenced).toBe(true); + }); + + it("the arrival and the move's queued messages leave the fence up; the user's own message here lifts it", async () => { + let model = await imported(); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + // The arrival kick, then the user's message from there. + let refusal: string | null; + ({ model, refusal } = await apply(model, sendQueued("m-arrival"))); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).queuedFollowUps).toHaveLength(1); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + model = await project(model, "thread.session-set", { + threadId: ARRIVED, + session: { + threadId: ARRIVED, + status: "ready", + providerName: "codex", + runtimeMode: "auto", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + }); + ({ model, refusal } = await apply( + model, + sendQueued(threadOf(model, ARRIVED).queuedFollowUps![0]!.messageId), + )); + expect(refusal).toBeNull(); + expect(threadOf(model, ARRIVED).queuedFollowUps ?? []).toHaveLength(0); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + + // Pull request auto-fix, and a restart's resume, are Threadlines' words, not the user's. + for (const extra of [{ keepsMoveFence: true }, { trigger: "serverRestart" }]) { + const decided = await Effect.runPromise( + decideOrchestrationCommand({ readModel: model, command: userTurn(extra) }), + ); + const planned = Array.isArray(decided) ? decided : [decided]; + const requested = planned.find((event) => event.type === "thread.turn-start-requested"); + expect(requested?.payload).not.toHaveProperty("liftsMoveFence"); + } + + ({ model } = await apply(model, userTurn())); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + // The rest of where it came from stays. + expect(threadOf(model, ARRIVED).movedFrom).toMatchObject({ label: "Mac mini" }); + }); +}); + 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 => diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 8bc2dcf7a..b22b9083d 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1850,6 +1850,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(pullRequestNumber === undefined ? {} : { pullRequestNumber }), ...(command.autoFix === undefined ? {} : { autoFix: command.autoFix }), ...(command.autoMerge === undefined ? {} : { autoMerge: command.autoMerge }), + // The user here set a switch, so the offer to turn on what was on + // before the move (Part 3e) has been answered. + ...(thread.movedFrom?.pullRequestSwitches === undefined + ? {} + : { clearsMovedSwitches: true as const }), updatedAt: occurredAt, }, }; @@ -3451,6 +3456,18 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.scheduledTaskId !== undefined ? { scheduledTaskId: command.scheduledTaskId } : {}), + // The user's own message on a thread that moved here fenced: they + // take it over (docs/design/fleet.md, Part 3e). A queued message the + // move carried, or one Threadlines wrote, never does (see + // thread.follow-up.send-queued). + ...(targetThread.movedFrom?.fenced === true && + command.fromThread === undefined && + command.fromOutside === undefined && + command.scheduledTaskId === undefined && + command.trigger === undefined && + command.keepsMoveFence !== true + ? { liftsMoveFence: true as const } + : {}), createdAt: command.createdAt, }, }; @@ -4142,10 +4159,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" 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 + .map((event): PlannedOrchestrationEvent => { + // What the move carried, or Threadlines wrote for it, isn't the + // user here taking the thread over: its fence stays. + if ( + (queued.afterMove === true || queued.imported === true) && + event.type === "thread.turn-start-requested" + ) { + const { liftsMoveFence: _lift, ...payload } = event.payload as Extract< + OrchestrationEvent, + { type: "thread.turn-start-requested" } + >["payload"]; + return { ...event, payload } as PlannedOrchestrationEvent; + } + return queued.afterMove === true && + event.type === "thread.message-sent" && + (event.payload as { readonly messageId?: unknown }).messageId === queued.messageId ? ({ ...event, payload: { @@ -4156,8 +4185,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" afterMove: true, }, } as PlannedOrchestrationEvent) - : event, - ), + : event; + }), ]; } // The agent's message was written when it was queued; sending it keeps diff --git a/apps/server/src/orchestration/linkFence.ts b/apps/server/src/orchestration/linkFence.ts new file mode 100644 index 000000000..f73e5eefb --- /dev/null +++ b/apps/server/src/orchestration/linkFence.ts @@ -0,0 +1,23 @@ +/** + * The linked-computer fence (docs/design/fleet.md, "Fence"): work that came + * from another computer gets no Threadlines tools here, so it can't reach + * other threads, schedules or this computer's settings. Two kinds of thread + * work behind it: one another computer's agent started here (`remoteOrigin`), + * for good, and one that moved here (`movedFrom.fenced`, Part 3e), until a + * message the user sends here starts a turn in it. Every place the fence + * applies asks this one rule. + */ +import type { OrchestrationThread } from "@threadlines/contracts"; + +export type LinkFencedThread = Pick; + +/** Whether the thread works behind the fence. */ +export const isLinkFenced = (thread: LinkFencedThread): boolean => + (thread.remoteOrigin ?? null) !== null || thread.movedFrom?.fenced === true; + +/** Why a fenced thread's agent can't use `tools` ("thread tools", "schedule tools"), in its words. */ +export function linkFenceRefusal(thread: LinkFencedThread, tools: string): string { + return (thread.remoteOrigin ?? null) !== null + ? `This thread was started by an agent on another computer, so it has no ${tools}.` + : `This thread moved here from ${thread.movedFrom?.label ?? "another computer"}, so it has no ${tools} until the user here sends it a message.`; +} diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 202163b6e..6461e6bd8 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -36,7 +36,7 @@ import { withUnqueuedAgentMessage, } from "@threadlines/shared/roomAgentRequests"; import { applyAgentPagePublication } from "@threadlines/shared/agentPages"; -import { nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; +import { movedFromAfter, nextThreadMoveState } from "@threadlines/shared/threadMoveProjection"; import { withQueuedFollowUp } from "@threadlines/shared/queuedFollowUps"; import { applyCommandRequestDismissed, @@ -569,15 +569,22 @@ export function projectEvent( autoFix, autoMerge, }), + ...(payload.clearsMovedSwitches === true + ? { movedFrom: movedFromAfter(thread.movedFrom, { clearsSwitches: true }) } + : {}), updatedAt: payload.updatedAt, }), }; } + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { ...(autoFix === undefined ? {} : { pullRequestAutoFix: autoFix }), ...(autoMerge === undefined ? {} : { pullRequestAutoMerge: autoMerge }), + ...(payload.clearsMovedSwitches === true && thread !== undefined + ? { movedFrom: movedFromAfter(thread.movedFrom, { clearsSwitches: true }) } + : {}), updatedAt: payload.updatedAt, }), }; @@ -1209,6 +1216,10 @@ export function projectEvent( ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { participants, + // The user here took a thread that moved here over: its fence lifts. + ...(payload.liftsMoveFence === true + ? { movedFrom: movedFromAfter(thread.movedFrom, { liftsFence: true }) } + : {}), // What the turn is sent with, and its messages stamped with. sentModels: recordTurnModel( { ...thread, participants }, diff --git a/apps/server/src/orchestration/threadMoveCarry.ts b/apps/server/src/orchestration/threadMoveCarry.ts index a9d4361e3..58fc5fce5 100644 --- a/apps/server/src/orchestration/threadMoveCarry.ts +++ b/apps/server/src/orchestration/threadMoveCarry.ts @@ -23,6 +23,7 @@ import type { } from "@threadlines/contracts"; import { PEER_MOVE_STATE_MAX_PLANS } from "@threadlines/contracts"; import { linkedPullRequestArmed } from "@threadlines/shared/linkedPullRequests"; +import { pullRequestSwitchesWords } from "@threadlines/shared/threadMoveProjection"; /** What a move view needs of a project to tell a General Chats thread. */ export interface ThreadMoveCarryView { @@ -196,35 +197,6 @@ export function carryNotTaken( 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. @@ -247,8 +219,13 @@ export function carryBringsWords(carry: ThreadMoveCarry): ReadonlyArray ); } if (carry.pullRequests !== null) { - const { words, verb, what } = pullRequestCarryWords(carry.pullRequests); - lines.push(`${words} ${verb} watching ${what} from there.`); + // They arrive off: only the user there turns them on (Part 3e, (c)). + const on = pullRequestSwitchesWords(carry.pullRequests); + if (on !== null) { + lines.push( + `${on.words} for ${on.what} ${on.plural ? "arrive" : "arrives"} off, for you to turn on there.`, + ); + } } if (carry.queuedFollowUps.length > 0) { lines.push( diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 126f03bdc..37e2c6810 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -1111,10 +1111,15 @@ function readOnlyCopyEvents( ]; } +/** The "Moved here" line's word on the fence a moved thread works behind (ThreadMovedFrom.fenced). */ +const MOVED_FENCE_WORDS = + "Its agent can't use other threads, rooms or schedules here until you send it a message."; + /** * A moved thread arriving: created with its history and the boundary that * says where it came from, in one decision. Refused when the thread exists, - * so a repeated import is no second copy. + * so a repeated import is no second copy. Every import comes from another + * computer, so the thread arrives fenced (docs/design/fleet.md, Part 3e). */ export function decideThreadImport( readModel: OrchestrationReadModel, @@ -1141,7 +1146,8 @@ export function decideThreadImport( interactionMode: command.interactionMode, branch: command.branch, worktreePath: command.worktreePath, - movedFrom: command.movedFrom, + // It came from another computer: fenced until the user here sends it a message. + movedFrom: { ...command.movedFrom, fenced: true }, historySeedOwed: true, ...(command.nativeSession !== undefined ? { nativeSession: command.nativeSession } : {}), createdAt: command.createdAt, @@ -1178,6 +1184,7 @@ export function decideThreadImport( payload: { threadId: command.threadId, activity: { ...activity, turnId: null } }, })); const arrival = command.arrival; + const left = [...(arrival?.left ?? []), MOVED_FENCE_WORDS]; const boundary: PlannedEvent = { ...base(), type: "thread.activity-appended", @@ -1199,7 +1206,7 @@ export function decideThreadImport( ...(arrival !== undefined && arrival.brought.length > 0 ? { brought: arrival.brought } : {}), - ...(arrival !== undefined && arrival.left.length > 0 ? { left: arrival.left } : {}), + left, }, turnId: null, createdAt: command.createdAt, @@ -1211,9 +1218,11 @@ export function decideThreadImport( /** * 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. + * 3e): its goal as it arrives, its pull requests, its plans, and its queue + * (the arrival message first). The pull requests' switches stay off whatever + * the command says: only the user here turns one on (the offer is + * `movedFrom.pullRequestSwitches`). 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">, @@ -1237,31 +1246,6 @@ function importedState( 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 ?? []) { @@ -1286,7 +1270,8 @@ function importedState( }, ] : []), - ...(command.queuedFollowUps ?? []), + // Sent there by the user, but here by the move: no turn of theirs lifts the fence. + ...(command.queuedFollowUps ?? []).map((entry) => ({ ...entry, imported: true as const })), ]; for (const followUp of queue) { events.push({ diff --git a/apps/server/src/scheduled/ScheduledTasks.ts b/apps/server/src/scheduled/ScheduledTasks.ts index cded34806..0c8216de7 100644 --- a/apps/server/src/scheduled/ScheduledTasks.ts +++ b/apps/server/src/scheduled/ScheduledTasks.ts @@ -121,6 +121,7 @@ import { import { ThreadBootstrap } from "../orchestration/Services/ThreadBootstrap.ts"; import { ProjectionTurnRepository } from "../persistence/Services/ProjectionTurns.ts"; import { derivedUuid } from "../orchestration/childRequestIds.ts"; +import { isLinkFenced } from "../orchestration/linkFence.ts"; import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts"; import { SystemWake } from "../power/Services/SystemWake.ts"; import { ServerSettingsService } from "../serverSettings.ts"; @@ -747,9 +748,11 @@ const make = Effect.gen(function* () { if (thread.projectId !== task.projectId) { return yield* taskError("The thread it should continue is in another project."); } - if ((thread.remoteOrigin ?? null) !== null) { + if (isLinkFenced(thread)) { return yield* taskError( - "A thread another computer started can't be continued on a schedule.", + (thread.remoteOrigin ?? null) !== null + ? "A thread another computer started can't be continued on a schedule." + : "A thread that moved here can't be continued on a schedule until you send it a message here.", ); } if (agentLeft(thread, task.target)) return yield* taskError(AGENT_LEFT_TASK); diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 6ac99605d..0182de1bb 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -46,6 +46,7 @@ import { createUserMessage, NOW_ISO, rpcHarness, + wsRequests, WIDE_FOOTER_VIEWPORT, isoAt, createSnapshotForTargetUser, @@ -520,7 +521,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { ); 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 github = "GitHub isn't signed in on Mac mini. Sign in there before you turn auto-fix on."; const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, snapshot: createSnapshotForTargetUser({ @@ -1458,6 +1459,60 @@ describe("ChatView (full app): moving a thread to another computer", () => { } }); + it("says which pull request switches were on before the move, and turns them on from here", async () => { + const pullRequest = { number: 212, url: "https://github.com/acme/w/pull/212" }; + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: withTestThread( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-moved-switches" as MessageId, + targetText: "moved with switches", + }), + { + linkedPullRequests: [{ ...pullRequest, autoFix: false, autoMerge: null }], + movedFrom: { + environmentId: FLEET_OFFLINE_ENVIRONMENT_ID, + label: "Mac mini", + threadId: "thread-on-mac-mini" as ThreadId, + movedAt: NOW_ISO, + fenced: true, + pullRequestSwitches: { + autoFix: false, + autoMerge: null, + linked: [{ ...pullRequest, autoFix: true, autoMerge: null }], + }, + }, + }, + ), + }); + + try { + await expect.element(page.getByText("Auto-fix is off.", { exact: true })).toBeInTheDocument(); + await expect + .element(page.getByText("It was on for pull request #212 on Mac mini.")) + .toBeInTheDocument(); + await page.getByRole("button", { name: "Turn on", exact: true }).click(); + await vi.waitFor(() => + expect( + wsRequests.filter( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + (request as { type?: string }).type === "thread.pull-request-automation.set", + ), + ).toMatchObject([ + { pullRequestNumber: 212, pullRequestUrl: pullRequest.url, autoFix: true }, + ]), + ); + // Left off instead: the notice goes, on this device. + await page.getByRole("button", { name: "Leave it off" }).click(); + await expect + .element(page.getByText("Auto-fix is off.", { exact: true })) + .not.toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + it("reads a request to move a thread as a move, in the thread being moved", async () => { const windowsLinks = fakeComputerLinksClient(); const request: ComputerLinkPendingRequest = { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index cc25471b2..3d1be6a73 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -357,6 +357,7 @@ import { import { type ComposerNotice, selectComposerNotices } from "./chat/composerNotices"; import { useMoveNotStartedNotice, + useMovedPullRequestSwitchesNotice, usePendingMoveNotice, useThreadMoveNotice, } from "./chat/threadMoveNotice"; @@ -7394,6 +7395,8 @@ export default function ChatView(props: ChatViewProps) { }); // A queued move that ended without starting says why until dismissed. const moveNotStartedNotice = useMoveNotStartedNotice({ thread: activeThread }); + // Pull request switches that were on before the move arrive off: Turn on. + const movedSwitchesNotice = useMovedPullRequestSwitchesNotice({ thread: activeThread }); // While a reply in chat answers the questions, the box says so, with the // way back to the card. const replyInChatNotice = useMemo( @@ -7431,12 +7434,14 @@ export default function ChatView(props: ChatViewProps) { removedAccountNotice, outsideWorkNotice, moveNotStartedNotice, + movedSwitchesNotice, ...infrastructureComposerNotices, ]), [ checkoutMissingNotice, infrastructureComposerNotices, moveNotStartedNotice, + movedSwitchesNotice, outsideWorkNotice, providerStatusNotice, removedAccountNotice, diff --git a/apps/web/src/components/chat/threadMoveNotice.tsx b/apps/web/src/components/chat/threadMoveNotice.tsx index d501cdf0f..53074ed4b 100644 --- a/apps/web/src/components/chat/threadMoveNotice.tsx +++ b/apps/web/src/components/chat/threadMoveNotice.tsx @@ -14,6 +14,9 @@ * when held). One that ended without starting says why ("Didn't move: …") * until the user dismisses it. * + * On the computer it lands on, a moved thread's pull request switches arrive + * off (Part 3e): a notice says what was on there, with Turn on. + * * @module threadMoveNotice */ import { @@ -25,6 +28,7 @@ import { type ThreadPendingMove, } from "@threadlines/contracts"; import { scopeThreadRef } from "@threadlines/client-runtime"; +import { pullRequestSwitchesWords } from "@threadlines/shared/threadMoveProjection"; import { useNavigate } from "@tanstack/react-router"; import * as Schema from "effect/Schema"; import { useCallback, useMemo, useState } from "react"; @@ -37,6 +41,7 @@ import { import { usePrimaryEnvironmentId } from "../../environments/primary"; import { useSavedEnvironmentRuntimeStore } from "../../environments/runtime"; import { useLocalStorage } from "../../hooks/useLocalStorage"; +import { turnOnMovedPullRequestSwitches } from "../../lib/threadPullRequestCommands"; import { useStore } from "../../store"; import { describePendingMove, @@ -431,3 +436,82 @@ export function useMoveNotStartedNotice(input: { [anotherMove, dismiss, dismissed, latest], ); } + +const MOVED_SWITCHES_DISMISSALS_STORAGE_KEY = "threadlines:moved-switches-dismissals:v1"; + +/** + * The pull request switches a thread had on before it moved here, which + * arrive off (docs/design/fleet.md, Part 3e, (c)): what was on there, with + * Turn on, which flips each one here as the user would. Gone once any switch + * is set here (the server clears the offer), or dismissed on this device. + */ +export function useMovedPullRequestSwitchesNotice(input: { + readonly thread: Pick | undefined; +}): ComposerNotice | null { + const { thread } = input; + const [dismissals, setDismissals] = useLocalStorage( + MOVED_SWITCHES_DISMISSALS_STORAGE_KEY, + { keys: [] }, + MoveNotStartedDismissalsSchema, + ); + const [turningOn, setTurningOn] = useState(null); + const movedFrom = thread?.movedFrom ?? null; + const switches = movedFrom?.pullRequestSwitches; + const on = useMemo( + () => (switches === undefined ? null : pullRequestSwitchesWords(switches)), + [switches], + ); + const dismissalKey = + thread && movedFrom ? `${thread.environmentId}:${thread.id}:${movedFrom.movedAt}` : null; + const dismissed = dismissalKey !== null && dismissals.keys.includes(dismissalKey); + const dismiss = useCallback(() => { + if (dismissalKey === null) return; + setDismissals((current) => + current.keys.includes(dismissalKey) + ? current + : { keys: [...current.keys, dismissalKey].slice(-MAX_MOVE_NOT_STARTED_DISMISSALS) }, + ); + }, [dismissalKey, setDismissals]); + const environmentId = thread?.environmentId ?? null; + const threadId = thread?.id ?? null; + const turnOn = useCallback(() => { + if (environmentId === null || threadId === null || switches === undefined) return; + setTurningOn(threadId); + void (async () => { + try { + await turnOnMovedPullRequestSwitches(scopeThreadRef(environmentId, threadId), switches); + } catch (error) { + toastManager.add( + failureNotice({ + title: "Couldn't turn them on", + reason: error instanceof Error ? error.message : "The server didn't answer.", + }), + ); + } finally { + setTurningOn((current) => (current === threadId ? null : current)); + } + })(); + }, [environmentId, switches, threadId]); + const busy = threadId !== null && turningOn === threadId; + const label = movedFrom?.label ?? null; + const movedAt = movedFrom?.movedAt ?? null; + return useMemo( + () => + on === null || label === null || dismissed + ? null + : { + id: `moved-pull-request-switches:${movedAt}`, + severity: "info", + lead: `${on.words} ${on.plural ? "are" : "is"} off.`, + detail: `${on.plural ? "They were" : "It was"} on for ${on.what} on ${label}.`, + actions: ( + + ), + dismissLabel: on.plural ? "Leave them off" : "Leave it off", + onDismiss: dismiss, + }, + [busy, dismiss, dismissed, label, movedAt, on, turnOn], + ); +} diff --git a/apps/web/src/lib/threadPullRequestCommands.ts b/apps/web/src/lib/threadPullRequestCommands.ts index f7732d09e..4cbc062d5 100644 --- a/apps/web/src/lib/threadPullRequestCommands.ts +++ b/apps/web/src/lib/threadPullRequestCommands.ts @@ -2,6 +2,7 @@ import type { DispatchResult, PullRequestMergeMethod, ScopedThreadRef, + ThreadMovedFrom, } from "@threadlines/contracts"; import { readEnvironmentApi } from "../environmentApi"; @@ -97,3 +98,38 @@ export async function setThreadPullRequestDismissed( dismissed, }); } + +/** + * Turn back on the switches a moved thread had on before its move + * (ThreadMovedFrom.pullRequestSwitches, docs/design/fleet.md, Part 3e): one + * `thread.pull-request-automation.set` per pull request, the user's own, as + * if each switch were flipped here. The first clears the offer. Rejects when + * the environment is not connected or a command is refused. + */ +export async function turnOnMovedPullRequestSwitches( + threadRef: ScopedThreadRef, + switches: NonNullable, +): Promise { + const api = readEnvironmentApi(threadRef.environmentId); + if (!api) { + throw new Error(`Environment ${threadRef.environmentId} is not connected.`); + } + const targets = [ + { pullRequest: null, autoFix: switches.autoFix, autoMerge: switches.autoMerge }, + ...switches.linked.map((entry) => ({ + pullRequest: { number: entry.number, url: entry.url }, + autoFix: entry.autoFix, + autoMerge: entry.autoMerge, + })), + ].filter((target) => target.autoFix || target.autoMerge !== null); + for (const target of targets) { + await api.orchestration.dispatchCommand({ + type: "thread.pull-request-automation.set", + commandId: newCommandId(), + threadId: threadRef.threadId, + ...switchTarget(target.pullRequest), + ...(target.autoFix ? { autoFix: true } : {}), + ...(target.autoMerge !== null ? { autoMerge: target.autoMerge } : {}), + }); + } +} diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index ca4ab4a1b..fbc59b241 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -99,6 +99,7 @@ import { import { getThreadFromEnvironmentState } from "./threadDerivation"; import { threadMoveStatus } from "./threadMove"; import { + movedFromAfter, nextThreadMoveState, type ThreadMoveEvent, type ThreadMoveState, @@ -719,7 +720,9 @@ function movedFromEqual( : a.environmentId === b.environmentId && a.label === b.label && a.threadId === b.threadId && - a.movedAt === b.movedAt; + a.movedAt === b.movedAt && + a.fenced === b.fenced && + JSON.stringify(a.pullRequestSwitches) === JSON.stringify(b.pullRequestSwitches); } /** The child-thread fields a sidebar row reads, from a shell or a loaded thread. */ @@ -2775,6 +2778,9 @@ function applyEnvironmentOrchestrationEvent( autoFix, autoMerge, }), + ...(event.payload.clearsMovedSwitches === true + ? { movedFrom: movedFromAfter(thread.movedFrom, { clearsSwitches: true }) } + : {}), updatedAt: event.payload.updatedAt, })); } @@ -2782,6 +2788,9 @@ function applyEnvironmentOrchestrationEvent( ...thread, ...(autoFix === undefined ? {} : { pullRequestAutoFix: autoFix }), ...(autoMerge === undefined ? {} : { pullRequestAutoMerge: autoMerge }), + ...(event.payload.clearsMovedSwitches === true + ? { movedFrom: movedFromAfter(thread.movedFrom, { clearsSwitches: true }) } + : {}), updatedAt: event.payload.updatedAt, })); } diff --git a/apps/web/src/threadMove.test.ts b/apps/web/src/threadMove.test.ts index 572ec6bf7..ddc4c7db0 100644 --- a/apps/web/src/threadMove.test.ts +++ b/apps/web/src/threadMove.test.ts @@ -223,7 +223,7 @@ describe("isThreadMoveOffered", () => { describe("what comes along", () => { it("keeps the notes for any agent, and those naming the agent picked", () => { const notes = [ - { words: "GitHub isn't signed in on Mac mini. Auto-fix waits there until you sign in." }, + { words: "GitHub isn't signed in on Mac mini. Sign in there before you turn auto-fix on." }, { words: "Codex on Mac mini can't set check-backs. It's told once what was planned.", instanceIds: ["codex"], diff --git a/docs/design/fleet.md b/docs/design/fleet.md index ab6bfa5e9..9578435ed 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -986,7 +986,7 @@ Nothing in Part 3's transfer, Part 3b's queue and barrier, Part 3c's batches or ### The rule -**What was going to run by itself here runs by itself there.** A goal that was working, a check-back that was due, a message waiting its turn, auto-fix watching a pull request: each keeps going on the other computer without the user setting it up again. A thread with none of these still arrives idle, as today. (Will's call 1 below: the default is that this starts work on arrival.) +**What was going to run by itself here runs by itself there, fenced.** A goal that was working, a check-back that was due, a message waiting its turn: each keeps going on the other computer without the user setting it up again, as far as the link's permission allows (its access ceiling caps the thread's mode). A thread with none of these still arrives idle, as today. (Will's call 1 below: the default is that this starts work on arrival.) Two things are the other computer's user's to give, not the move's (Security changes, below): pull request switches arrive off, and the thread works behind the link fence (no Threadlines tools) until that user sends it a message. Three more rules follow from the requirements: @@ -996,14 +996,14 @@ Three more rules follow from the requirements: ### What each one does -| The thread has | What happens | Still refused | -| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| (a) A goal | **Carried.** The goal, its budget and its counts come along. One that was working is picked up there by itself. One the user had paused arrives paused, with Resume. | Nothing. An agent picked there that can't keep goals gets none: the arrival line says so and quotes the goal. | -| (b) Check-backs | **Set up again there.** The agent's timers end with its process here. On arrival the agent is told what it had planned and when, and sets them again itself. | Nothing. An agent picked there that can't set check-backs is still told once, on arrival. | -| (c) Pull request auto-fix or auto-merge | **Carried.** The switches and the linked pull requests come along and start watching there. They stop here when the thread freezes. | Nothing. They arrive switched off, with why, when the thread's branch had to be renamed there. | -| (d) A General Chats thread | **Carried.** The chat and every file in its folder land in General chats on the other computer. | A folder over the move's 100 MB limit, with its size. | -| (e) Queued messages | **Carried.** The user's own queued messages wait here while the move waits, travel with their attachments, and are sent there in order. | A queued message from a scheduled task, another thread or an outside assistant: "…is waiting its turn. Move once it has been sent, or remove it." | -| (f) A plan waiting | **Carried.** The thread's plans come along. The waiting one arrives waiting, and Implement and Dismiss work there. | Nothing. | +| The thread has | What happens | Still refused | +| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| (a) A goal | **Carried.** The goal, its budget and its counts come along. One that was working is picked up there by itself. One the user had paused arrives paused, with Resume. | Nothing. An agent picked there that can't keep goals gets none: the arrival line says so and quotes the goal. | +| (b) Check-backs | **Set up again there.** The agent's timers end with its process here. On arrival the agent is told what it had planned and when, and sets them again itself. | Nothing. An agent picked there that can't set check-backs is still told once, on arrival. | +| (c) Pull request auto-fix or auto-merge | **Linked, off.** The linked pull requests come along; every switch arrives off. The thread's notice there says what was on, with Turn on. They stop here at the freeze. | Nothing. When the branch had to be renamed there, there is no Turn on: the arrival line says why. | +| (d) A General Chats thread | **Carried.** The chat and every file in its folder land in General chats on the other computer. | A folder over the move's 100 MB limit, with its size. | +| (e) Queued messages | **Carried.** The user's own queued messages wait here while the move waits, travel with their attachments, and are sent there in order. | A queued message from a scheduled task, another thread or an outside assistant: "…is waiting its turn. Move once it has been sent, or remove it." | +| (f) A plan waiting | **Carried.** The thread's plans come along. The waiting one arrives waiting, and Implement and Dismiss work there. | Nothing. | All of it only when the other computer says it takes it (Capabilities). Against an older computer, every one of these is refused exactly as today. @@ -1012,16 +1012,16 @@ All of it only when the other computer says it takes it (Capabilities). Against - **Move dialog** (single thread and batch). Under the agent line from Part 3d, one quiet line per thing that comes along, in the server's words: - "Its goal carries on there." or "Its goal arrives paused." - "Its agent sets its 2 check-backs again there." - - "Auto-fix keeps watching pull request #212 from there." + - "Auto-fix for pull request #212 arrives off, for you to turn on there." - "2 queued messages are sent there." - "The plan waits for you there." - General Chats: "Lands in General chats on Windows PC · 14 files". The branch and "Staged changes arrive as unstaged changes" lines don't show. - **Warnings**, same place, when something won't work as it did: - - "GitHub isn't signed in on Windows PC. Auto-fix waits there until you sign in." + - "GitHub isn't signed in on Windows PC. Sign in there before you turn auto-fix on." - "Codex on Windows PC can't set check-backs. It's told once what was planned." - Claude with a working goal: "It's working toward its goal. Move when it's done waits until it gets there." - **The batch dialog and the quit dialog** (Part 3c) stop greying these threads out. Working General Chats threads are listed with the project threads. -- **On the other computer**, the "Moved here from Mac" line lists what arrived ("its goal · 2 queued messages · auto-fix for #212") and, on a second line, anything that didn't ("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."). +- **On the other computer**, the "Moved here from Mac" line lists what arrived ("its goal · 2 queued messages · pull request #212") and, on a second line, anything that didn't, or waits for the user there ("Auto-fix was on for pull request #212 on Mac. It's off here until you turn it on." "Its agent can't use other threads, rooms or schedules here until you send it a message."). A notice above the message box says the same about the switches, with Turn on. - **The arrival message.** When the agent has to be told something (a goal to carry on with, check-backs to set again), the first message on the other computer is one Threadlines wrote. It shows as a quiet system-written row, like the "Continue where you left off." row after a restart, not as something the user typed. - **On this computer**, the read-only copy shows no queue, no armed switches and no goal controls. If the move didn't happen: "The move to Windows PC didn't happen. Your goal and check-backs are back on here." @@ -1115,14 +1115,14 @@ Not for `gone` (the thread was archived or deleted). To make this rare, the queu ### (c) Pull request auto-fix and auto-merge -**Decision: carry the switches, stop them here at the freeze.** GitHub-side auto-merge (`gh pr merge --auto`) lives on GitHub and needs nothing. +**Decision: carry the links, not the switches; stop them here at the freeze.** (Changed by the security review, below: this section first carried the switches on.) GitHub-side auto-merge (`gh pr merge --auto`) lives on GitHub and needs nothing. - **Here.** `PullRequestAutomationWatcher` skips any thread with `pendingMove` or `move`: no look, no baseline step, no turn, no merge. Today it knows nothing of moves. Its merge is a direct `gh` call that no command guard sees, so an armed frozen thread would still merge from this computer. A turn refused by the move guard also still steps the baseline, which would swallow a failure. `decideMoveComplete` turns the switches off on the read-only copy (`thread.pull-request-automation-changed`). A dropped move leaves them on, and the watcher picks up where its baseline was. - **Manifest:** `thread.state.pullRequests { autoFix, autoMerge, linked: [{ number, url, autoFix, autoMerge }] }`, and `git.upstreamBranch?` (the branch on the project's remote that this branch tracks). -- **Import:** `thread.pull-request-linked` for each, then `thread.pull-request-automation-changed`, in the import decision. The watcher there sees a switch turned on while it runs, so it treats what is failing now as news. That is the right start: a check that failed during the move gets fixed. Its turn cap starts again. +- **Import:** `thread.pull-request-linked` for each, every switch off. What was on goes to `movedFrom.pullRequestSwitches`; the thread's notice and the arrival line offer it, and Turn on sends the normal `thread.pull-request-automation.set` from the user's client, once per pull request. Any switch set there clears the offer (`clearsMovedSwitches` on `thread.pull-request-automation-changed`). The watcher sees a switch turned on while it runs, so it treats what is failing now as news. Its turn cap starts again. - **The branch keeps its upstream.** The import creates the branch with no upstream today. The thread's own pull request is found by upstream name, else by local name, and the "wait for unpushed commits" guard before a merge compares against the upstream. A moved thread can arrive with commits that were never pushed. At the `worktree` stage, when `/` exists after the fetch, the import sets `branch..remote` and `.merge`. For every move, not only armed ones. -- **Arrives off, with why,** when the branch had to be renamed (`-from-`): a plain push from it would not reach the pull request. Also when the upstream couldn't be set on an armed thread. -- **No GitHub sign-in there** (Will's call 2). Default: move anyway, switches on, and say so at both ends. The watcher there fails quietly today (logs only), so the arrival line carries it: "Auto-fix came along, but GitHub isn't signed in on this computer. Sign in and it starts." +- **No Turn on, with why,** when the branch had to be renamed (`-from-`): a plain push from it would not reach the pull request. Also when the upstream couldn't be set on an armed thread. +- **No GitHub sign-in there** (Will's call 2). Move anyway, and say so at both ends: "GitHub isn't signed in on this computer. Sign in before you turn them on." - **Asking the target.** New `peer.move.readiness { canonicalKey } → { gitHubReady?: boolean }`, called by the preview only for a thread with armed switches and a target with `moveThreadState`. It runs the probe behind `server.discoverSourceControl`. Not on `peer.describe`: every preview would pay for a `gh` call. - **Risks.** - Whether `remoteStatus` reports unpushed commits with no upstream is unverified. If it reports none, auto-merge could merge a pull request that lacks the thread's local commits. Setting the upstream closes it. Test it with a real repo. @@ -1195,7 +1195,7 @@ Not for `gone` (the thread was archived or deleted). To make this rare, the queu Each has a default written into this plan, so the build can start. Changing one is small. 1. **Work starts on arrival.** Default: yes. A goal that was working, check-backs and queued messages make the other computer start a turn by itself when the thread lands (under Ask first, when its user allows the move). That spends that computer's usage with nobody watching, which is what a goal or a check-back already does. The other choice: everything arrives held, with one "Pick up here" button on the thread. It is the same build with the kick moved from `LinkMoves` to that button. -2. **Auto-fix, and the other computer has no GitHub sign-in.** Default: warn and move. Refusing would block a shutdown over something fixable later, and the switches would sit idle on a computer that is off anyway. +2. **Auto-fix, and the other computer has no GitHub sign-in.** Default: warn and move. Refusing would block a shutdown over something fixable later. (The switches arrive off now either way: Security changes, below.) 3. **Check-backs Claude saved to disk.** Default: bring them like the others, through the arrival message. The copy Claude saved stays in this computer's folder. The other choice: keep refusing those, with the honest words. 4. **General Chats files.** Default: every file in the chat's folder, up to 100 MB, refused above that with the size. The other choice: offer "move without its files". 5. **A live check on real agents.** Three facts decide details here and can't be read from our code: whether Claude re-arms a goal on a forked resume, where it keeps saved check-backs, and how Codex takes a goal set during a turn. Checking them needs a few real Claude and Codex turns. Without an OK the build follows this plan's safe side (set the goal when the provider holds none; "Run CronList" first) and the report says a real resume is unverified. @@ -1270,6 +1270,29 @@ These win over the text above where they differ. - Every proposed plan is carried, up to 100. Past that, the oldest stay behind, and the dialog and the "Moved here" line say "N older plans stayed on ". - The newest plan, the one with Implement, always comes. +### Security changes (Nov 17, PR #976 review) + +These win over everything above in Part 3e. What a move carries came from another computer, so it gets no more trust than work that computer's agent starts here over the link. + +1. **Pull request switches arrive off, every one.** + - A switch acts with this computer's GitHub sign-in: auto-fix starts turns, auto-merge merges. The other computer can't turn one on here. + - The linked pull requests still come along, so the thread's pull request rows show. + - What was on rides in `ThreadMovedFrom.pullRequestSwitches`. The "Moved here" line says it ("Auto-fix was on for pull request #212 on Mac. It's off here until you turn it on."). So does a notice above the message box, with Turn on and a dismiss. + - Turn on sends the normal `thread.pull-request-automation.set` from the user's client, one per pull request. Never from the peer. + - Any switch the user sets here clears the offer (`clearsMovedSwitches`). +2. **A moved thread works behind the link fence until the user here takes it over.** + - The import sets `ThreadMovedFrom.fenced`. A new optional field, not a new kind of thread. + - Every place that fences a thread another computer's agent started (`remoteOrigin`) fences this one too, through one rule (`orchestration/linkFence.ts`): + - the room and guide tools the reactor gives the agent; + - the thread and room tool handlers' guard, `thread_read` and `thread_list` included; + - the schedule tools; + - continuing it on a schedule. + - Work still picks up on arrival as the link's permission allows, fenced. Its mode stays capped by the link's access ceiling, as before. + - **The fence lifts** when a message the user sent on this computer starts a turn in the thread: `liftsMoveFence` on that `thread.turn-start-requested`, which clears `fenced` in every projection. A restart keeps whatever the projection holds. + - **What doesn't lift it:** the arrival message, queued messages the move carried (`imported` on the queued entry), and anything Threadlines or an agent sends: another thread, an outside assistant, a scheduled task, a restart or usage-limit resume, pull request auto-fix (`keepsMoveFence`). + - A session started fenced is restarted with resume at the next start after the lift, so the agent gets its tools. + - The "Moved here" line says it: "Its agent can't use other threads, rooms or schedules here until you send it a message." + ## Part 4: The rail and the Fleet page ### Rail diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 19dc9247e..54d0d1e7f 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1105,6 +1105,33 @@ export const ThreadMovedFrom = Schema.Struct({ label: TrimmedNonEmptyString, threadId: ThreadId, movedAt: IsoDateTime, + /** + * What it carried came from another computer, so it works fenced, as a + * thread another computer's agent started here does (ThreadRemoteOrigin): + * no Threadlines tools, until a message the user sends here starts a turn + * (docs/design/fleet.md, Part 3e). Absent: not fenced (anymore). + */ + fenced: Schema.optional(Schema.Literal(true)), + /** + * The pull request switches that were on there. They arrive off: a switch + * acts with this computer's GitHub sign-in, so only this computer's user + * turns it on (`thread.pull-request-automation.set`, which clears this). + * Absent: none was on, or they were turned on here since. + */ + pullRequestSwitches: Schema.optional( + Schema.Struct({ + autoFix: Schema.Boolean, + autoMerge: Schema.NullOr(PullRequestMergeMethod), + linked: Schema.Array( + Schema.Struct({ + number: PositiveInt, + url: TrimmedNonEmptyString, + autoFix: Schema.Boolean, + autoMerge: Schema.NullOr(PullRequestMergeMethod), + }), + ), + }), + ), }); export type ThreadMovedFrom = typeof ThreadMovedFrom.Type; @@ -2264,6 +2291,12 @@ export const OrchestrationQueuedFollowUp = Schema.Struct({ overtakes: Schema.optional(MessageId), /** See OrchestrationMessage.afterMove: kept so the message is written with it when sent. */ afterMove: Schema.optional(Schema.Literal(true)), + /** + * Carried from another computer by a move (docs/design/fleet.md, Part 3e): + * written by the user there, not here, so sending it doesn't lift the + * thread's fence (ThreadMovedFrom.fenced). + */ + imported: Schema.optional(Schema.Literal(true)), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, createdAt: IsoDateTime, @@ -3812,6 +3845,11 @@ export const ThreadTurnStartCommand = Schema.Struct({ trigger: Schema.optional(MessageTrigger), /** Server only: a scheduled or event task's run sent it (see ThreadTurnStartRequestedPayload). */ scheduledTaskId: Schema.optional(ScheduledTaskId), + /** + * Server only: Threadlines wrote it (pull request auto-fix), not the user, + * so it doesn't lift a moved thread's fence (ThreadMovedFrom.fenced). + */ + keepsMoveFence: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); @@ -5385,6 +5423,8 @@ const ThreadImportCommand = Schema.Struct({ * 3e), all with this computer's ids. `goal` is written as it arrives * (working, paused or finished); the queue is written behind the arrival * message and isn't sent by its events (the move's own kick sends it). + * `pullRequests` links them; their switches are written off whatever they + * say here (see ThreadMovedFrom.pullRequestSwitches). */ goal: Schema.optional(OrchestrationThreadGoal), pullRequests: Schema.optional( @@ -5780,6 +5820,12 @@ export const ThreadPullRequestAutomationChangedPayload = Schema.Struct({ pullRequestNumber: Schema.optional(PositiveInt), autoFix: Schema.optional(Schema.Boolean), autoMerge: Schema.optional(Schema.NullOr(PullRequestMergeMethod)), + /** + * The user set a switch on a thread that moved here with switches on + * there: what was on there (ThreadMovedFrom.pullRequestSwitches) is no + * longer offered. + */ + clearsMovedSwitches: Schema.optional(Schema.Literal(true)), updatedAt: IsoDateTime, }); @@ -6274,6 +6320,11 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ * the message does not carry it. */ scheduledTaskId: Schema.optional(ScheduledTaskId), + /** + * The user's own message on this computer starts this turn in a thread + * that moved here fenced (ThreadMovedFrom.fenced): the fence lifts. + */ + liftsMoveFence: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); diff --git a/packages/shared/src/threadMoveProjection.ts b/packages/shared/src/threadMoveProjection.ts index 3eb61cde4..74899706d 100644 --- a/packages/shared/src/threadMoveProjection.ts +++ b/packages/shared/src/threadMoveProjection.ts @@ -21,6 +21,7 @@ import type { OrchestrationThreadMove, ThreadMoveOutcome, ThreadMoveOutcomeReason, + ThreadMovedFrom, ThreadPendingMove, } from "@threadlines/contracts"; @@ -215,3 +216,84 @@ export function nextThreadMoveState( ? state : { move, pendingMove, lastMoveOutcome }; } + +/** + * Where a moved thread came from, after the user here took it over (the + * fence lifts: `liftsMoveFence`) or set one of its pull request switches + * (what was on there is no longer offered: `clearsMovedSwitches`). The same + * object when neither changes it. Every reader of those events applies it. + */ +export function movedFromAfter( + movedFrom: T, + change: { readonly liftsFence?: boolean; readonly clearsSwitches?: boolean }, +): T { + if (movedFrom === null || movedFrom === undefined) return movedFrom; + const lift = change.liftsFence === true && movedFrom.fenced !== undefined; + const clear = change.clearsSwitches === true && movedFrom.pullRequestSwitches !== undefined; + if (!lift && !clear) return movedFrom; + const { fenced, pullRequestSwitches, ...rest } = movedFrom; + return { + ...rest, + ...(lift || fenced === undefined ? {} : { fenced }), + ...(clear || pullRequestSwitches === undefined ? {} : { pullRequestSwitches }), + } as T; +} + +/** A thread's pull request switches, as a move carries them (own switch, then each linked one). */ +export interface MovedPullRequestSwitches { + readonly autoFix: boolean; + readonly autoMerge: unknown; + readonly linked: ReadonlyArray<{ + readonly number: number; + readonly autoFix: boolean; + readonly autoMerge: unknown; + }>; +} + +/** + * Which pull request switches are on, in words: `words` ("Auto-fix", + * "Auto-merge", or both), whether that is more than one switch (`plural`), + * and what they watch (`what`: "pull request #212", "this thread's pull + * request"). Null: none is on. + */ +export function pullRequestSwitchesWords(switches: MovedPullRequestSwitches): { + readonly words: string; + readonly plural: boolean; + readonly what: string; +} | null { + const armed = switches.linked.filter((entry) => entry.autoFix || entry.autoMerge !== null); + const own = switches.autoFix || switches.autoMerge !== null; + const fix = switches.autoFix || armed.some((entry) => entry.autoFix); + const merge = switches.autoMerge !== null || armed.some((entry) => entry.autoMerge !== null); + if (!fix && !merge) return null; + const numbers = armed.map((entry) => `#${entry.number}`); + const what = + numbers.length === 0 + ? "this thread's pull request" + : own + ? `this thread's pull request and ${numbers.join(", ")}` + : numbers.length === 1 + ? `pull request ${numbers[0]}` + : `pull requests ${numbers.join(", ")}`; + return { + words: fix && merge ? "Auto-fix and auto-merge" : fix ? "Auto-fix" : "Auto-merge", + plural: fix && merge, + what, + }; +} + +/** + * What the "Moved here" line and the moved thread's notice say about the + * switches that were on before the move: they arrive off (docs/design/fleet.md, + * Part 3e, (c)). Null: none was on. + */ +export function movedPullRequestSwitchesWords( + switches: MovedPullRequestSwitches, + fromLabel: string, +): string | null { + const on = pullRequestSwitchesWords(switches); + if (on === null) return null; + return on.plural + ? `${on.words} were on for ${on.what} on ${fromLabel}. They're off here until you turn them on.` + : `${on.words} was on for ${on.what} on ${fromLabel}. It's off here until you turn it on.`; +}