From d897d793d88c71568506c5f6accd68e3393663de Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 05:32:46 +0000 Subject: [PATCH] fix(fork): resolve upstream merge e9c952495c (2026-11-23) Resolve the 17 conflicts that commit A left from merging upstream e9c952495c, and fix what the merge broke elsewhere. This is stage 1 of a staged catch-up: one fork change is dropped for now (below). Each conflict keeps upstream's code and puts the fork's change back on top. Where both sides changed one behaviour: - Upstream #41490 keeps a compaction or manual continuation busy like a turn, which the fork's startBusyTurn did for account-change restarts. Upstream's busyTurn replaces it; the fork keeps releaseIfAccountChanged. - Upstream #41184 keeps the reading position when side panels resize. The chat timeline keeps the fork's reader line, which covers that case and more; running both made two correctors pull on one scroll node. Upstream's helper still serves the composer. Its timeline test waits until the scroll has settled, as the reader line requires. - Upstream #41537 keeps a PDF's place on resize; the fork's restore echo and saved width stay on top. - Upstream #41317 removes the changed-files card under assistant turns; the fork's edited mark and sub-thread reply line stay. - Upstream #41552 captures MCP tool results for providers that drop them. The fork's send_to_user goes through it; upstream's capture test calls the fork's tool. A Chat-mode reply, ack or rewrite succeeds with no result the capture keeps, so it records an empty result: a refused call with the same arguments can then no longer pass its error to a delivered reply. The ACP adapter keeps a result the provider reported over an empty recovered one. - Upstream #41362 finishes a run when the provider turn ends, not after checkpoint capture. The fork's per-attempt checkpoint capture id (a run restarted by a late steer still completes) breaks upstream's steering tests and its own pin no longer holds, so this stage drops it and its pin; a follow-up decides whether it is still needed. - Upstream #41307 shows a queued message whose cancelled run had started. The fork's Chat history and sub-thread counts take the same rule, and the display-mode wrap test models a cancelled queued turn as never started. - Upstream #41330 deletes three internal docs that the fork had extended; they stay deleted, and the fork's notes from them (outbox order, the Antigravity summarization recovery, the `fyi` send mode) move to the fork-only fork/docs/internals.md. Fork tests follow upstream's new interfaces (setup-script runner, Antigravity profile directory, removed onOpenTurnDiff, hasCompletedRun), and agentContextBudget.json holds the measured values. Upstream adds database migration 111_SupersededRunAttemptIndex. Co-Authored-By: Claude Opus 5.5 --- .../displayModeWrap/DisplayModeWrap.test.ts | 3 +- .../src/fork/fyi/FyiRuntimeLayer.test.ts | 9 +- .../fork/shownHistory/ShownHistory.test.ts | 42 +- .../src/fork/shownHistory/ShownHistory.ts | 3 +- apps/server/src/fork/subThreads/SubThreads.ts | 7 +- .../fork/userMessageTools/SendToUser.test.ts | 41 +- .../src/fork/userMessageTools/SendToUser.ts | 7 + apps/server/src/git/GitManager.test.ts | 3 - apps/server/src/mcp/McpHttpServer.ts | 9 +- apps/server/src/mcp/OrchestratorMcpService.ts | 3 - apps/server/src/mcp/toolkits/core.test.ts | 20 +- .../Adapters/AntigravityAdapterV2.test.ts | 7 +- .../src/orchestration-v2/Orchestrator.ts | 2 +- .../ProviderSessionManager.test.ts | 5 - .../ProviderSessionManager.ts | 31 +- .../ProviderTurnStartService.test.ts | 19 +- .../ProviderTurnStartService.ts | 4 - .../orchestration-v2/RunExecutionService.ts | 2 +- .../SteeringCompletion.integration.test.ts | 124 +--- .../src/provider/agentContextBudget.json | 8 +- apps/server/src/vcs/GitVcsDriverCore.ts | 11 +- .../src/components/chat/MarkdownFileLink.tsx | 6 +- .../chat/MessagesTimeline.browser.test.tsx | 8 + .../src/components/chat/MessagesTimeline.tsx | 19 - .../components/chat/TimelineAssistantRows.tsx | 19 - apps/web/src/components/files/PdfViewer.tsx | 14 +- .../displayModeTimeline.browser.test.tsx | 1 - .../displayMode/useThreadDisplayMode.test.ts | 1 + .../idleCompactionTimeline.browser.test.tsx | 1 - .../web/src/fork/singleTilde.browser.test.tsx | 1 - .../fork/timelineReaderLine.browser.test.tsx | 1 - docs/internals/overview.md | 163 ----- docs/internals/providers.md | 189 ----- .../orchestrator-mcp-server.md | 659 ------------------ fork/docs/internals.md | 66 ++ packages/provider-acp/src/server/adapter.ts | 3 +- 36 files changed, 209 insertions(+), 1302 deletions(-) delete mode 100644 docs/internals/overview.md delete mode 100644 docs/internals/providers.md delete mode 100644 docs/orchestration-v2/orchestrator-mcp-server.md create mode 100644 fork/docs/internals.md diff --git a/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts b/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts index aca3ec1a92f87..dfcdb88cee947 100644 --- a/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts +++ b/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts @@ -175,7 +175,8 @@ const runCreated = ( activeAttemptId: threadId === sourceId ? attemptId : null, status, requestedAt: now, - startedAt: now, + // A cancelled run here is a queued turn that never started. + startedAt: status === "cancelled" ? null : now, completedAt: status === "completed" ? now : null, checkpointId: null, contextHandoffId: null, diff --git a/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts b/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts index c802c01940407..e9e73c6101643 100644 --- a/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts +++ b/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts @@ -45,6 +45,7 @@ import * as ThreadCommandExecutor from "../../orchestration-v2/ThreadCommandExec import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProjectService from "../../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../../project/ProjectSetupScriptRunner.ts"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import * as ModelManifest from "../../provider/ModelManifest.ts"; import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegistry.ts"; @@ -55,8 +56,12 @@ import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../../vcs/VcsProcess.ts"; import * as FyiDelivery from "./FyiDelivery.ts"; -const layerPlatformTest = Layer.merge( - Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), +const layerPlatformTest = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" }), + }), Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ resolveLink: () => Effect.die("unused title link"), }), diff --git a/apps/server/src/fork/shownHistory/ShownHistory.test.ts b/apps/server/src/fork/shownHistory/ShownHistory.test.ts index 4686c5ab2a43b..28e6f9b2e75e4 100644 --- a/apps/server/src/fork/shownHistory/ShownHistory.test.ts +++ b/apps/server/src/fork/shownHistory/ShownHistory.test.ts @@ -92,6 +92,7 @@ const LARGE = ThreadId.make("thread:shown:large"); const REWRITES = ThreadId.make("thread:shown:rewrites"); const HUGE = ThreadId.make("thread:shown:huge"); const SPLIT = ThreadId.make("thread:shown:split"); +const CANCELLED = ThreadId.make("thread:shown:cancelled"); const runIdOf = (threadId: ThreadId, run: number) => RunId.make(`run:${threadId}:${run}`); const nodeIdOf = (threadId: ThreadId, run: number) => NodeId.make(`node:${threadId}:${run}`); @@ -145,7 +146,8 @@ function threadCreated( function runEvent( threadId: ThreadId, run: number, - status: "completed" | "failed" | "rolled_back" = "completed", + status: "completed" | "failed" | "rolled_back" | "cancelled" = "completed", + started = true, ): OrchestrationV2DomainEvent { const runId = runIdOf(threadId, run); return { @@ -168,7 +170,7 @@ function runEvent( activeAttemptId: null, status, requestedAt: at, - startedAt: at, + startedAt: started ? at : null, completedAt: at, checkpointId: null, contextHandoffId: null, @@ -664,6 +666,23 @@ const CHILDREN = [ ["a child whose shown rows end on a batch boundary", CHILD_EDGE, 16, 8, PARENT], ] as const; +const queuedMessage = (threadId: ThreadId, run: number, text: string): OrchestrationV2TurnItem => ({ + ...base(threadId, run, 1), + ...TYPED, + type: "user_message", + messageId: messageIdOf(threadId, run, 1), + inputIntent: "queued_turn", + text, + attachments: [], +}); +/** Run 2 started and a restart then cancelled it; run 3 was cancelled before it started. */ +const cancelledThread = () => [ + userMessage(CANCELLED, 1, 1, "Fix the build."), + send(CANCELLED, 1, 2, "On it."), + queuedMessage(CANCELLED, 2, "Also check the logs."), + queuedMessage(CANCELLED, 3, "Never mind this."), +]; + const runsOf = (items: ReadonlyArray) => [ ...new Set(items.map((item) => Number(String(item.runId).split(":").at(-1)))), ]; @@ -694,6 +713,7 @@ const seed = Effect.gen(function* () { [REWRITES, rewritesThread(), threadCreated(REWRITES)], [HUGE, hugeThread(), threadCreated(HUGE)], [SPLIT, splitThread(), threadCreated(SPLIT)], + [CANCELLED, cancelledThread(), threadCreated(CANCELLED)], ]; for (const [threadId, items, created] of threads) { yield* projections.apply(created); @@ -702,6 +722,8 @@ const seed = Effect.gen(function* () { } yield* projections.apply(runEvent(PARENT, ROLLED_BACK_RUN, "rolled_back")); yield* projections.apply(runEvent(GUARD, 3, "failed")); + yield* projections.apply(runEvent(CANCELLED, 2, "cancelled")); + yield* projections.apply(runEvent(CANCELLED, 3, "cancelled", false)); for (const run of range(1, 3)) yield* projections.apply(runEvent(QUIET, run, "failed")); yield* projections.apply({ id: EventId.make("event:shown:question"), @@ -1226,6 +1248,22 @@ it.layer(TestLayer)("shown-only history", (it) => { assert.isTrue(page.items.some((row) => !isShownItem(row.item))); }), ); + it.effect("shows a queued message whose cancelled run had started, as Normal does", () => + Effect.gen(function* () { + const normal = visibleIds( + boundedSnapshotProjection( + yield* firstSnapshot({ threadId: CANCELLED, acceptBoundedSnapshot: true }), + ), + ); + const shown = visibleIds(boundedSnapshotProjection(yield* shownSnapshot(CANCELLED))); + const delivered = String(itemIdOf(CANCELLED, 2, 1)); + const held = String(itemIdOf(CANCELLED, 3, 1)); + assert.include(normal, delivered); + assert.notInclude(normal, held); + assert.include(shown, delivered); + assert.notInclude(shown, held); + }), + ); }); function runOrdinalOf(item: Pick): number { diff --git a/apps/server/src/fork/shownHistory/ShownHistory.ts b/apps/server/src/fork/shownHistory/ShownHistory.ts index 77d0868ad4d90..ccd207018982d 100644 --- a/apps/server/src/fork/shownHistory/ShownHistory.ts +++ b/apps/server/src/fork/shownHistory/ShownHistory.ts @@ -201,7 +201,8 @@ const segmentVisible = (sql: SqlClient.SqlClient, segment: ShownSegment) => ? sql`(run.status IS NULL OR run.status <> 'rolled_back') AND NOT (item.type = 'user_message' AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' - AND run.status IS 'cancelled')` + AND run.status IS 'cancelled' + AND json_extract(run.payload_json, '$.startedAt') IS NULL)` : sql`(run.ordinal <= ${segment.inherited.runOrdinal} OR (item.run_id IS NULL AND ${segment.inherited.runlessRows ? 1 : 0} = 1))`; diff --git a/apps/server/src/fork/subThreads/SubThreads.ts b/apps/server/src/fork/subThreads/SubThreads.ts index 593c8030e06e8..2ca38551f4849 100644 --- a/apps/server/src/fork/subThreads/SubThreads.ts +++ b/apps/server/src/fork/subThreads/SubThreads.ts @@ -256,7 +256,12 @@ export const layerFromServices = Layer.effect( ${userTypedSql(sql)} AND (run.status IS NULL OR run.status <> 'rolled_back') AND NOT ( - COALESCE(run.status IN ('queued', 'cancelled'), 0) + COALESCE( + run.status = 'queued' OR ( + run.status = 'cancelled' AND json_extract(run.payload_json, '$.startedAt') IS NULL + ), + 0 + ) AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' ) `; diff --git a/apps/server/src/fork/userMessageTools/SendToUser.test.ts b/apps/server/src/fork/userMessageTools/SendToUser.test.ts index 8add053fdf87e..f7afb57b7c349 100644 --- a/apps/server/src/fork/userMessageTools/SendToUser.test.ts +++ b/apps/server/src/fork/userMessageTools/SendToUser.test.ts @@ -9,7 +9,8 @@ import { TurnItemId, } from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; -import { shortId } from "@t3tools/shared/displayModes"; +import { displayEventFromTurnItem, shortId } from "@t3tools/shared/displayModes"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -456,3 +457,41 @@ describe("replace_send_to_user", () => { }).pipe(Effect.provide(layer)), ); }); + +// A provider that drops MCP outputs gets each send's result back from the capture by its input. +describe("Chat sends through the MCP result capture", () => { + const captureLayer = layer.pipe(Layer.provideMerge(McpProviderSessions.layer)); + const reply = { + text: "Fixed the build.", + reply_to: shortId("u1"), + user_message: "Fix the build.", + }; + const recoveredEvent = Effect.gen(function* () { + const sessions = yield* McpProviderSessions.McpProviderSessions; + const output = yield* sessions.takeToolResult(chatThread, "send_to_user", reply); + return displayEventFromTurnItem({ + ...base("recovered"), + type: "dynamic_tool", + toolName: "mcp__t3-code__send_to_user", + input: reply, + output, + } as never)?.type; + }); + + it.effect("keeps a reply shown when an identical later send was refused", () => + Effect.gen(function* () { + history = [typed("u1", "Fix the build.")]; + expect((yield* answerU1(reply.text)).isError).not.toBe(true); + expect((yield* answerU1(reply.text)).isError).toBe(true); + expect(yield* recoveredEvent).toBe("sent"); + }).pipe(Effect.provide(Layer.fresh(captureLayer))), + ); + + it.effect("shows a lone reply", () => + Effect.gen(function* () { + history = [typed("u1", "Fix the build.")]; + expect((yield* answerU1(reply.text)).isError).not.toBe(true); + expect(yield* recoveredEvent).toBe("sent"); + }).pipe(Effect.provide(Layer.fresh(captureLayer))), + ); +}); diff --git a/apps/server/src/fork/userMessageTools/SendToUser.ts b/apps/server/src/fork/userMessageTools/SendToUser.ts index 185d2f1f019a5..f45aa34c72cea 100644 --- a/apps/server/src/fork/userMessageTools/SendToUser.ts +++ b/apps/server/src/fork/userMessageTools/SendToUser.ts @@ -191,6 +191,13 @@ const ReplaceSendToUserTool = Tool.make(REPLACE_SEND_TO_USER_TOOL_NAME, { export const SendToUserToolkit = Toolkit.make(SendToUserTool, ReplaceSendToUserTool); +// A Chat-mode success keeps no field the MCP result capture reads. Its empty record stops an +// identical refused call's error from passing for it when a provider drops both outputs. +export const capturedSuccessFallback = (toolName: string): Record | undefined => + toolName === SEND_TO_USER_TOOL_NAME || toolName === REPLACE_SEND_TO_USER_TOOL_NAME + ? {} + : undefined; + /** The items stored before the calling tool use, when the provider names it; else all of them. */ function itemsBefore(shown: ReadonlyArray, ownItem: string | undefined) { const ownAt = diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 85d46aedbb857..d26e3752a3348 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -31,11 +31,8 @@ import type { GitActionProgressEvent, GitPreparePullRequestThreadInput, ModelSelection, -<<<<<<< origin/main ServerSettings as ServerSettingsValue, -======= ServerProvider, ->>>>>>> upstream/main } from "@t3tools/contracts"; import { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 00e05a14b365d..3ff0f223ea9c3 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1266,7 +1266,8 @@ const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(f } const output = exit._tag === "Success" - ? compactT3McpToolOutput(toolName, exit.value) + ? (compactT3McpToolOutput(toolName, exit.value) ?? + SendToUser.capturedSuccessFallback(toolName)) : { isError: true }; return output === undefined ? Effect.void @@ -1417,15 +1418,11 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); -<<<<<<< origin/main // The fork's send_to_user replaces upstream's: display modes read its calls by name and `text`. -const layerMessageToolkit = toolkitRegistration( +export const layerMessageToolkit = toolkitRegistration( SendToUser.SendToUserToolkit, SendToUser.layerHandlers, ); -======= -export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); ->>>>>>> upstream/main const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a445936549aea..54230d629bb41 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -138,11 +138,8 @@ import { taskPrompt, } from "./delegatedTaskModes.ts"; import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; -<<<<<<< origin/main import { fyiRunsByThread, fyiTimelineFields, sendFyi } from "../fork/fyi/FyiMcp.ts"; -======= import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts"; ->>>>>>> upstream/main import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index c1d35ace86940..5a946c60a6f83 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -57,6 +57,7 @@ import * as SecretRequests from "../../secrets/SecretRequests.ts"; import * as RemoteDelegation from "../../peer/RemoteDelegation.ts"; import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts"; import * as ServerSettings from "../../serverSettings.ts"; +import { DisplayModeWrap } from "../../fork/displayModeWrap/DisplayModeWrap.ts"; import * as McpHttpServer from "../McpHttpServer.ts"; import * as McpInvocationContext from "../McpInvocationContext.ts"; import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts"; @@ -422,28 +423,28 @@ it.effect("captures send_to_user results for providers that drop MCP outputs", ( const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const draft = "### Status\n\nAll checks passed."; const result = yield* server - .callTool({ name: "send_to_user", arguments: { message: draft } }) + .callTool({ name: "send_to_user", arguments: { text: draft } }) .pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, scope), Effect.provideService(McpSchema.McpServerClient, client), ); expect(result.isError).not.toBe(true); - expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual( - { sentMessage: draft }, - ); - expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe( + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toEqual({ + sentMessage: draft, + }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toBe( undefined, ); const invalid = yield* server - .callTool({ name: "send_to_user", arguments: { message: "" } }) + .callTool({ name: "send_to_user", arguments: { text: "" } }) .pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, scope), Effect.provideService(McpSchema.McpServerClient, client), Effect.flip, ); expect(invalid).toMatchObject({ _tag: "InvalidParams" }); - expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({ + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: "" })).toEqual({ isError: true, }); }).pipe( @@ -452,6 +453,11 @@ it.effect("captures send_to_user results for providers that drop MCP outputs", ( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provideMerge(McpProviderSessions.layer), Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + // The fork's send_to_user reads the thread's display mode. + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mock(DisplayModeWrap)({ forgetNotesAfterCompaction: () => (ingest) => ingest }), + ), ), ), ), diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 10fc8c9cf7109..ed7c69d39cd81 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,17 +13,13 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -<<<<<<< origin/main -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; -import * as Digest from "effect/crypto/Digest"; -======= import { compactDynamicToolOutput, htmlRenderFromToolItem, previewRecordingIdFromToolItem, sentMessageFromToolItem, } from "@t3tools/shared/toolOutput"; ->>>>>>> upstream/main +import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -1072,6 +1068,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { const unfinishedText = "Still running when turn ended."; const adapter = yield* makeAntigravityAdapterV2({ instanceId, + profileDirectory: unusedProfileDirectory, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => makeAntigravityAcpRuntime({ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 9b81ce5cb562b..aff0021d6c61c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13579,7 +13579,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* Ref.update(input.effects, (effects) => [ ...effects, { - id: `effect:checkpoint.capture:${attempt.id}`, + id: `effect:checkpoint.capture:${run.id}`, commandId: CommandId.make(`command:effect:checkpoint.capture:${run.id}`), threadId: input.command.threadId, request: { diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index dde71a5999d9d..a397dc32dbce6 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -615,13 +615,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( resumeCount: current.resumeCount + 1, })).pipe(Effect.as(threadInput.providerThread)), startTurn: () => options.startTurn ?? Effect.void, -<<<<<<< origin/main - compactThread: () => Effect.void, - resumeTurn: () => Effect.void, -======= resumeTurn: () => options.startTurn ?? Effect.void, compactThread: () => options.startTurn ?? Effect.void, ->>>>>>> upstream/main steerTurn: () => Effect.void, interruptTurn: () => Ref.update(state, (current) => ({ diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b83ce0755af55..42bdaebbe4a15 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2553,7 +2553,7 @@ export const layerWithOptions = ( ReadonlyMap> >, ): ProviderAdapter.ProviderAdapterV2SessionRuntime => { - const { providerSessionId, compactThread, resumeTurn } = runtime; + const providerSessionId = runtime.providerSessionId; const subscribeEvents = makeEventSubscription(eventSubscribers); const turnMetrics = (operation: string, model?: string) => withMetrics({ @@ -2565,11 +2565,6 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); -<<<<<<< origin/main - const startBusyTurn = ( - input: ProviderAdapter.ProviderAdapterV2TurnInput, - start: Effect.Effect, -======= // A start, continuation or compaction keeps the session busy until its turn.terminal. const busyTurn = ( input: Pick< @@ -2577,7 +2572,6 @@ export const layerWithOptions = ( "threadId" | "providerThread" | "runOrdinal" | "runId" >, run: () => Effect.Effect, ->>>>>>> upstream/main ) => observeActivity( providerSessionId, @@ -2624,11 +2618,7 @@ export const layerWithOptions = ( ), ), ), -<<<<<<< origin/main - () => start, -======= run, ->>>>>>> upstream/main (_, exit) => Exit.isFailure(exit) ? observeActivity( @@ -2780,30 +2770,12 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => -<<<<<<< origin/main - startBusyTurn( - input, -======= busyTurn(input, () => ->>>>>>> upstream/main agentFeedbackMode.pipe( Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), turnMetrics("send", input.modelSelection.model), ), ), -<<<<<<< origin/main - ...(compactThread === undefined - ? {} - : { - compactThread: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => - startBusyTurn(input, compactThread(input)), - }), - ...(resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - startBusyTurn(ProviderAdapter.resumeTurnInput(input), resumeTurn(input)), -======= ...(runtime.resumeTurn === undefined ? {} : { @@ -2823,7 +2795,6 @@ export const layerWithOptions = ( turnMetrics("compact", input.modelSelection.model), ), ), ->>>>>>> upstream/main }), steerTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 53fe3c6ed8dc5..92b347090dac5 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -185,11 +185,10 @@ function startWithMissingWorktree( Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), -<<<<<<< origin/main Layer.succeed( FileSystem.FileSystem, FileSystem.makeNoop({ - exists: () => Effect.succeed(false), + exists: () => Effect.succeed(worktreeExists), realPath: (target: string) => normalize(target) in realPaths ? Effect.succeed(realPaths[normalize(target)]) @@ -203,22 +202,6 @@ function startWithMissingWorktree( ), } as never), ), -======= - Layer.succeed(FileSystem.FileSystem, { - exists: () => Effect.succeed(worktreeExists), - realPath: (target: string) => - normalize(target) in realPaths - ? Effect.succeed(realPaths[normalize(target)]) - : Effect.fail( - PlatformError.systemError({ - _tag: "NotFound", - module: "FileSystem", - method: "realPath", - pathOrDescriptor: target, - }), - ), - } as never), ->>>>>>> upstream/main layerWorktreeLocation(), layerNoTaskFolders, Layer.mock(GitWorkflow.GitWorkflowService)({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 32cd960dd4817..91e9b6f0b04b1 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -45,16 +45,12 @@ import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; -<<<<<<< origin/main import * as DisplayModeWrap from "../fork/displayModeWrap/DisplayModeWrap.ts"; import * as FyiDelivery from "../fork/fyi/FyiDelivery.ts"; -import { makeRestoreMissingWorktree } from "../workspace/restoreMissingWorktree.ts"; -======= import { makeRestoreMissingWorktree, ThreadWorktreeRestore, } from "../workspace/restoreMissingWorktree.ts"; ->>>>>>> upstream/main import type * as TaskFolders from "../workspace/TaskFolders.ts"; import * as EventSink from "./EventSink.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index eec3a8cce0a3f..46e0485d4014b 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -883,7 +883,7 @@ export const layer: Layer.Layer< input.terminal.status === "cancelled" ? [ { - id: `effect:checkpoint.capture:${input.attempt.id}`, + id: `effect:checkpoint.capture:${input.run.id}`, commandId: checkpointCaptureCommandId, threadId: input.run.threadId, request: { diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 81cd52359059e..f642cabbbc2c4 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -527,7 +527,6 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* turn: ProviderAdapter.ProviderAdapterV2SteerInput, ) => Effect.Effect = () => Effect.void, extraAdapters: ReadonlyArray = [], - beforeSelectionTransition: Effect.Effect = Effect.void, ) { const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode"); const cwd = yield* checkpointWorkspace(name); @@ -550,8 +549,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* instanceId, driver, getCapabilities: () => Effect.succeed(capabilities), - planSelectionTransition: () => - beforeSelectionTransition.pipe(Effect.as({ type: "apply_on_next_turn" as const })), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (input) => Effect.gen(function* () { const now = yield* DateTime.now; @@ -1410,126 +1408,6 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect.each(["completed", "interrupted"] as const)( - "checkpoints a run that a steer restarted before its first answer was checkpointed (restart %s)", - (restartEnd) => - Effect.gen(function* () { - const steerReadRunning = yield* Deferred.make(); - const letSteerCommit = yield* Deferred.make(); - const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `steer-restart-before-checkpoint-${restartEnd}`, - true, - false, - Effect.void, - true, - undefined, - undefined, - [], - Deferred.succeed(steerReadRunning, undefined).pipe( - Effect.andThen(Deferred.await(letSteerCommit)), - ), - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const outbox = yield* EffectOutbox.EffectOutboxV2; - const threadId = yield* startFirstTurn; - const runId = started[0]!.runId; - const runReaches = (status: string) => - orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === runId && - event.payload.status === status, - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - const endTurn = ( - turn: ProviderAdapter.ProviderAdapterV2TurnInput, - status: "completed" | "interrupted", - ) => - Effect.gen(function* () { - const providerTurn = (yield* orchestrator.getThreadProjection( - threadId, - )).providerTurns.find((candidate) => candidate.runAttemptId === turn.attemptId)!; - const finalized = yield* runReaches(status === "completed" ? "waiting" : status); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { ...providerTurn, status, completedAt: yield* DateTime.now }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver, - providerThreadId: providerTurn.providerThreadId, - providerTurnId: providerTurn.id, - runOrdinal: turn.runOrdinal, - status, - failure: null, - threadDisposition: "reusable", - }); - yield* Fiber.join(finalized); - }); - - const steer = yield* orchestrator - .dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer-after-settle"), - threadId, - messageId: MessageId.make("message:steer-after-settle"), - text: "also check the logs", - attachments: [], - modelSelection: composerSelection, - dispatchMode: { type: "steer_active", targetRunId: runId }, - createdBy: "agent", - creationSource: "mcp", - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(steerReadRunning); - yield* endTurn(started[0]!, "completed"); - const restartRunning = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "provider-turn.updated" && - event.payload.status === "running" && - event.payload.runAttemptId !== started[0]!.attemptId, - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* Deferred.succeed(letSteerCommit, undefined); - yield* Fiber.join(steer); - // The first answer's capture finds the run restarting and retries until it gives up; the - // restarted attempt starts behind it on the thread's effect lane. - for (const delay of [0, 100, 200, 400, 800]) { - yield* TestClock.adjust(delay); - yield* worker.drain(); - } - yield* Fiber.join(restartRunning); - yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); - assert.equal(started.length, 2); - assert.equal(started[1]!.runId, runId); - - yield* endTurn(started[1]!, restartEnd); - // Startup recovery keeps a waiting run alive only if it finds a pending capture by this id. - const captures = yield* outbox.listByCommandId( - CommandId.make(`command:effect:checkpoint.capture:${runId}`), - ); - assert.equal(captures.filter((capture) => capture.status === "pending").length, 1); - yield* worker.drain(); - const run = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (candidate) => candidate.id === runId, - ); - assert.equal(run?.status, restartEnd); - assert.notEqual(run?.checkpointId, null); - }).pipe(Effect.provide(layer)); - }), -); - it.effect.each(["complete", "stop-before-end"] as const)( "starts a steer that missed the turn in its place on the saved next-turn selection: %s", (timing) => diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 0cbbf6d9d9ee9..f9f8bfa7b0e3f 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,11 +1,5 @@ { -<<<<<<< origin/main "claudeSystemAppendBytes": 5945, "codexAdditionalContextBytes": 7339, - "mcpToolListJsonBytes": 67360 -======= - "claudeSystemAppendBytes": 6245, - "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 61709 ->>>>>>> upstream/main + "mcpToolListJsonBytes": 67345 } diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index c3060c95ee158..71c05547b9259 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -48,17 +48,8 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; -<<<<<<< origin/main -import { - explicitBareRepositoryEnv, - gitConfigEnv, - unsetInheritedRepositoryEnv, -} from "./VcsProcess.ts"; -import { makeWorktreeCheckoutSites } from "../fork/reflinkWorktrees/worktreeCheckoutSites.ts"; -======= import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts"; -import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; ->>>>>>> upstream/main +import { makeWorktreeCheckoutSites } from "../fork/reflinkWorktrees/worktreeCheckoutSites.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; import { diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 901ea3168578e..c9fafd8722648 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -11,8 +11,7 @@ import { memo, useState, type MouseEvent as ReactMouseEvent } from "react"; import { useGT } from "gt-react"; import { FolderIcon } from "lucide-react"; -<<<<<<< origin/main -import { contextMenuSourceOf } from "../../contextMenuSource"; +import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../../contextMenuSource"; import { hostFileLinkMenuItems, leavesFileChipClickToBrowser, @@ -20,9 +19,6 @@ import { } from "../../fork/hostFileLinks"; import { fileChipPanelLink } from "../../fork/rightPanelSplit/linkSources"; import { type OpenedSurface, startPanelLinkDrag } from "../../fork/rightPanelSplit/panelLinkDrag"; -======= -import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../../contextMenuSource"; ->>>>>>> upstream/main import { readLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links"; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index c901186dcc397..670a407deef70 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -658,6 +658,14 @@ describe("MessagesTimeline messages", () => { viewport.dispatchEvent(new Event("scroll")); const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; expect(Math.abs(before - 24)).toBeLessThan(2); + // The fork's reader line holds the line only once the scroll has rested for 100 ms. + let rested = 0; + let lastTop = Number.NaN; + await vi.waitFor(() => { + rested = viewport.scrollTop === lastTop ? rested + 1 : 0; + lastTop = viewport.scrollTop; + expect(rested).toBeGreaterThanOrEqual(3); + }); for (const width of [500, 900]) { screen.container.style.width = `${width}px`; await vi.waitFor(() => { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c322d799fda8e..28c9d35653f49 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -28,7 +28,6 @@ import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/s import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import type { FyiCarrierRun } from "@t3tools/client-runtime/fork/fyi-marker"; import { observeResize } from "~/lib/observeResize"; -import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { useStableCallback } from "~/hooks/useStableCallback"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; @@ -1279,7 +1278,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; -<<<<<<< origin/main const attachReaderLine = useTimelineReaderLine(readerLineRef, { liveFollowEnabled, findActive, @@ -1288,16 +1286,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ listIdentityKey, onHoldEnd: handleScroll, }); -======= - const shouldPreserveReadingPosition = useStableCallback( - () => - !liveFollowEnabled && - !anchoredEndSpace && - !findActive && - !citationPositioning && - !restoringThreadPosition, - ); ->>>>>>> upstream/main // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1313,13 +1301,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; -<<<<<<< origin/main const detachReaderLine = viewport ? attachReaderLine(viewport) : undefined; -======= - const stopPreservingReadingPosition = scrollNode - ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition) - : undefined; ->>>>>>> upstream/main const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1349,7 +1331,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ scheduleContentSizeChanged(); return () => { stopListeningToContentSize?.(); - stopPreservingReadingPosition?.(); stopRememberingRelease?.(); stopDisclosureReveal?.(); if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame); diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 77fa03dc16f18..ccd7451132bbf 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -24,18 +24,10 @@ import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; -<<<<<<< origin/main -import { useAtomValue } from "@effect/atom-react"; -import { AsyncResult, Atom } from "effect/reactivity"; -import { vcsEnvironment } from "../../state/vcs"; import { SubThreadMetaReply, SubThreadReplyLine } from "../../fork/subThreads/SubThreadReplyLine"; import { AgentMessageDivider } from "../../fork/displayMode/AgentMessageDivider"; import { EditedMark } from "../../fork/displayMode/EditedMark"; -const NO_VCS_STATUS = Atom.make(AsyncResult.initial()); -======= ->>>>>>> upstream/main - export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const gt = useGT(); @@ -82,19 +74,8 @@ export function AssistantTimelineRow({ row }: { row: Extract -<<<<<<< origin/main - {ctx.onOpenTurnDiff ? ( - - ) : null} -======= ->>>>>>> upstream/main {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index dd8f0ceda2aaf..e7535d11a30b0 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -381,14 +381,9 @@ export default function PdfViewer(props: { top: pdfRestoredScrollTop(ratios, width, initialView, initialView.width), left: initialView.left, }); -<<<<<<< origin/main restored.current = { top: node.scrollTop, left: node.scrollLeft }; - setScrollTop(node.scrollTop); - saveView(node, false); -======= setScrolled({ top: node.scrollTop, width, pdf }); - saveView(node); ->>>>>>> upstream/main + saveView(node, false); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits. useLayoutEffect(() => { @@ -583,9 +578,8 @@ export default function PdfViewer(props: { tabIndex={0} className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40" onScroll={(event) => { -<<<<<<< origin/main const top = event.currentTarget.scrollTop; - setScrollTop(top); + setScrolled({ top, width, pdf }); // The restore's own scroll event lands where the restore put the view. const echo = restored.current; restored.current = null; @@ -593,10 +587,6 @@ export default function PdfViewer(props: { event.currentTarget, echo?.top !== top || echo.left !== event.currentTarget.scrollLeft, ); -======= - setScrolled({ top: event.currentTarget.scrollTop, width, pdf }); - saveView(event.currentTarget); ->>>>>>> upstream/main }} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "f") { diff --git a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx index af72174a28980..d858608526063 100644 --- a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx +++ b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx @@ -110,7 +110,6 @@ function props(): Omit { turnDiffSummaries: [], runs: [], routeThreadKey: `environment-local:display-mode-${Math.random().toString(36).slice(2)}`, - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts index a0b8761592f29..0e20c9db867a7 100644 --- a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts +++ b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts @@ -34,6 +34,7 @@ const menuState: ThreadActionMenuState = { canSnoozeNow: true, isRegeneratingTitle: false, isRunning: false, + hasCompletedRun: true, supports: { settlement: true, autoSettleOptOut: true, diff --git a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx index fb4654c66c175..8840c1e4dcb0a 100644 --- a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx +++ b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx @@ -102,7 +102,6 @@ describe("whileIdle compaction in the timeline", () => { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-while-idle" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/singleTilde.browser.test.tsx b/apps/web/src/fork/singleTilde.browser.test.tsx index cf415cbc7404e..77511f698447e 100644 --- a/apps/web/src/fork/singleTilde.browser.test.tsx +++ b/apps/web/src/fork/singleTilde.browser.test.tsx @@ -133,7 +133,6 @@ function singleTildeTimeline(stage: Stage) { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-single-tilde" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/timelineReaderLine.browser.test.tsx b/apps/web/src/fork/timelineReaderLine.browser.test.tsx index 4cbbfbd8de2cd..8f00b86785fac 100644 --- a/apps/web/src/fork/timelineReaderLine.browser.test.tsx +++ b/apps/web/src/fork/timelineReaderLine.browser.test.tsx @@ -68,7 +68,6 @@ function props(listRef: TimelineProps["listRef"]): Omit {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/docs/internals/overview.md b/docs/internals/overview.md deleted file mode 100644 index e10a977a6bc3a..0000000000000 --- a/docs/internals/overview.md +++ /dev/null @@ -1,163 +0,0 @@ -# Architecture - -T3 Code keeps execution in the environment that owns the workspace. Web, desktop, and mobile -clients control it over authenticated RPC. A remote client must never substitute its own filesystem, -provider credentials, or machine state for the environment's. The desktop app bundles a server, -but its renderer follows the same boundary. - -## Ownership boundaries - -Provider processes, terminals, Git, and project files belong to the server. Shared connection and -domain state belongs in `packages/client-runtime`; clients supply platform services and UI. -Keeping that logic shared prevents reconnect and multi-environment behavior from diverging between -web and mobile. See [connection runtime](./connection-runtime.md) and -[remote environments](./remote.md). - -The [RPC contract](../../packages/contracts/src/rpc.ts) is the boundary between independently -versioned clients and servers. Subscriptions send the state a client needs, so a client viewing one -thread does not pay for every thread's history. Authentication of a socket does not authorize every -method on it. See [environment auth](./environment-auth.md). - -### Pull request linking compatibility - -Every protocol-2 environment advertises `threadPullRequests`. Once an environment's server config -has loaded, clients use persisted `pullRequests[]`, multi-link commands, stack UI, and reverse thread -lookup. Before that, they hide linking actions. - -Environments keep advertising `threadPullRequestLinking`, accepting legacy metadata commands, and -emitting the derived `linkedPullRequest` field, because older clients still read them. That -hostless field includes only links in the thread project's own repository. Retain the legacy wire -fields, projection column, and replay support. - -Provider-specific behavior belongs behind an adapter. Orchestration works with normalized commands -and events, so adding a provider should not require branches throughout the domain or clients. -See [provider constraints](./providers.md). - -## Settings ownership - -Client preferences stay in the current client; environment defaults and project overrides stay -on their owning server. The web and desktop settings target is URL state, resolved against current -connections and project membership. An unavailable target must not fall back to another environment. -**All environments** is an explicit bulk edit of connected, loaded servers, not a durable global -default or a promise to synchronize offline or future environments. Project-group targets similarly -select known environment-local checkouts; the group itself does not store inherited defaults. - -## Durable intent and side effects - -Orchestration state is decided as events, and projections are the source of truth once they apply -them. The [v2 orchestrator](../../apps/server/src/orchestration-v2/Orchestrator.ts) serializes commands and -decides events without performing provider or filesystem work. -[EventSink](../../apps/server/src/orchestration-v2/EventSink.ts) commits events, persisted projections, -the accepted command receipt, and outbox effects in one database transaction. Subscribers receive -events after that commit. This keeps command retries idempotent and prevents a persisted projection -from getting ahead of the event log. - -The [effect worker](../../apps/server/src/orchestration-v2/EffectWorker.ts) performs side effects -after intent has been recorded, then feeds results back into orchestration. A command acknowledgement -therefore means the intent committed, not that the provider, checkpoint, or other follow-up work -finished. Keep external I/O out of command decisions and the database transaction. Effects tied to -a lost provider process cannot simply replay; recovery retires them before admitting new work. - -A thread's effects run in outbox order: a pending effect, even one whose `available_at` is hours -away, blocks every later effect of its thread (title generation has its own lane). A long timer is -therefore a [Scheduler](../../apps/server/src/scheduling/Scheduler.ts) sweep, as in -[UsageLimitRecoveryWorker](../../apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts), not -a delayed outbox effect. - -The event log only keeps what live readers need: about a day of history for reconnect replay and -command-id retries. -[ProjectionMaintenance](../../apps/server/src/orchestration-v2/ProjectionMaintenance.ts) deletes -older events the projections cover, so projections cannot be rebuilt from the log. It keeps each -stream's newest event (high-water marks, stream versions, snapshot sequences), `thread.created` -(the legacy importer's marker), every `running` run update (Codex usage history reads the first -of each attempt), and prompt anchors that retained subagent rows reference. A client whose cursor -is below both its thread's newest event and the recorded pruned-through sequence missed pruned -events, so it resumes from a snapshot; an idle thread's cursor resumes without one. Resumes -recheck that sequence after reading the replay, since a pass can prune during the read. V2 command -receipts stay for idempotency: a retry older than the retained history is still deduplicated, -but its replay comes back without the pruned events. Receipts of imported legacy commands are -removed once their threads are imported. - -Retained events must remain decodable on replay. Changing a schema affects old environments at -startup as well as live RPC traffic. Compatibility work must account for stored history, not just -what the newest client sends. - -## Turn completion and checkpoints - -A provider turn ending and its follow-up work settling are separate milestones. Orchestration -records provider turn and run state independently from -[run finalization](../../apps/server/src/orchestration-v2/RunFinalizationService.ts). A late -checkpoint or diff must not extend the recorded provider duration or keep the client showing -provider work as active. PR discovery after completion also checks that the checkout still matches -the thread's non-default branch and that a newer run is not active. - -[Checkpoints](../../apps/server/src/checkpointing/CheckpointStore.ts) use hidden Git refs to -capture workspace state without adding commits to the user's branch. A revert must coordinate -workspace state with the provider conversation. A provider that cannot roll back its conversation -must reject that operation before changing the filesystem. - -A thread also gets one `repository` checkpoint scope per tracked Git folder it reaches, under its -root scope. A project can track dozens of repositories while a -turn touches a few, so these scopes are sparse: a turn costs one `git status` per repository, and -only a repository the turn changed gets a snapshot ref, a `checkpoint.captured` record and, the -first time, its `checkpoint-scope.created`. A missing record means the turn left the repository -alone, and a ref does not exist for every run ordinal. - -A file rewind restores the thread's folder and every repository a discarded run changed, or none -of them: each folder is snapshotted first and put back if a later restore fails. A repository -with no checkpoint at the target returns to the baseline taken before its first later change, -which `repositoryRewindCheckpoint` picks; one whose earlier state was never snapshotted is left as -it is. Run ordinals are never reused, so the snapshots of discarded runs are deleted rather than -overwritten. - -A worktree thread of a project that tracks Git folders works in a task folder: one directory under -the worktrees directory that holds the project folder and a worktree of each chosen repository at -the same relative places, all on the thread's branch. The record is keyed by that directory, not -by thread, because subagents, forks and reused worktrees share a path. Such a thread reaches only -those worktrees: a repository scope's `cwd` is the worktree and its `repositoryPath` the tracked -folder. A project folder that is not a repository root is never checked out; its entries are -linked, so they stay shared with the original. Its root checkpoints are `missing` by design, and -a file rewind there restores the repositories alone. `TaskFolders` owns every change to a task folder, -and removal keeps any checkout the single-worktree rules would keep. - -Thread settlement is server-owned. The -[settlement service](../../apps/server/src/orchestration-v2/ThreadSettlementService.ts) evaluates PR -and inactivity settings without a connected client. Merge notifications invalidate cached PR state -and trigger a check. A merge outside T3, such as an agent running `gh pr merge`, sends no -notification, so the [PR sync reactor](../../apps/server/src/orchestration-v2/PullRequestSyncReactor.ts) -re-reads a thread's open links when a run that ran a merge or close command ends. Each forge's -definition names its CLI's commands in `changeRequestCloseCommand`. The guarded -`thread.auto-settle` command rejects newer activity, explicit settlement overrides, and live or -blocked work. It records the activity timestamp for stable -sorting and detaches idle provider sessions. Clients render the persisted result; they do not -derive settlement from their own clocks or PR caches. - -## Waiting for asynchronous work - -Tests use [drainable workers](../../packages/shared/src/DrainableWorker.ts) to wait until both the -queue and its current item have finished. An empty queue alone does not prove the worker is idle. - -V2 tests also drain the effect worker or await a specific persisted event or receipt. Test signals -are separate from the durable command receipts that make dispatch idempotent. Production behavior -must use persisted state and events, not test instrumentation or assumptions about elapsed time. - -The Electron shell acquires `DesktopPreReadyPlatform.layer` synchronously before asynchronous -services. On Linux this sets the desktop-entry identity and global-shortcut portal flags before -Chromium initializes its portal connection. Setting the identity later in `DesktopAppIdentity` -is too late: Chromium caches the first registration, including failures. The identity must match -the installed entry managed by `DesktopLinuxUrlHandler`. Pre-ready setup also refreshes that entry's -`Exec` path before portal registration: AppImage updates can remove the previous executable, which -makes the old entry invalid even though its filename is correct. The later URL handler avoids -rewriting an identical entry while the portal may be reading it. On Wayland, Electron's synchronous -shortcut-registration result only confirms submission; it does not confirm desktop consent or -an active binding. - -Native modules never load in the Electron main process on the startup path, and the two the -snapshot feature keeps are isolated: `@crowecawcaw/xa11y` runs only in forked Node-mode children -(`SnapShotAccessibilityWorker`, `RegionSnapShotWorker`) and a worker thread, and `ffi-rs` loads -lazily inside `WindowsForeground.ts` for a handful of Win32 calls. macOS window lookup shells out -to `osascript` instead of a native addon. A crash or stall in any of these must not take the app -down, so new native capability goes in a child with a deadline, not an `import` in main. - -See the [glossary](./glossary.md) for shared terms and the -[development runbook](../operations/development.md) for setup and checks. diff --git a/docs/internals/providers.md b/docs/internals/providers.md deleted file mode 100644 index 735c5fbdcc12e..0000000000000 --- a/docs/internals/providers.md +++ /dev/null @@ -1,189 +0,0 @@ -# Provider constraints - -Orchestration records intent and state without knowing which provider runs a thread. Provider -protocols, account ownership, permissions, and capabilities belong at the -[adapter boundary](../../packages/provider-core/src/server/ProviderAdapter.ts). Normalize there -instead of spreading provider checks through orchestration and clients. - -A driver kind identifies an integration; an instance identifies one configuration and account -lifecycle. Route work by instance, so two accounts using the same driver do not share mutable -session or catalog state. For a new driver, start with [adding a provider](./adding-a-provider.md). - -## Process and account isolation - -The `opencode` driver probes the installed version and runs the 1.x or 2.x runtime. OpenCode's MCP -registrations are directory-scoped, while T3's MCP connection is thread-scoped, so threads in one -directory must not share one T3 MCP entry. - -- **1.x** uses one T3-managed chat server per thread, so threads cannot replace each other's - connection. Catalog and text-generation work can share the - [instance-owned helper](../../packages/provider-opencode/src/server/OpenCodeServerOwner.ts), which closes - after an idle period. See the [1.x adapter](../../packages/provider-opencode/src/server/adapter.ts). -- **2.x** serves every directory from one - [server per instance](../../packages/provider-opencode/src/server/v2/OpenCode2Server.ts). Each thread - registers its own `t3-code-` MCP entry, and session permission rules deny every other - thread's entry. See the [2.x adapter](../../packages/provider-opencode/src/server/v2/adapter.ts). - -External OpenCode servers remain externally owned and can require an external restart to pick up -configuration changes. OpenCode stores "always" approval grants for the whole project. Automatic -full-access replies use `once` so they cannot widen a supervised thread's permissions on a shared -server. On 2.x, a session-wide approval also replies `once` and becomes T3's own rule on that session. - -Pi runs the user's own `pi` install in RPC mode and owns native extension, package, and project -trust discovery. T3 injects only its namespaced MCP bridge, so a Pi session behaves as it does in -the Pi TUI. Pi session files back native resume, rollback, and same-instance thread forks. -Forks use Pi's CLI in the destination directory because RPC session switching retains the source -session's cwd. Provider switches still use portable handoff summaries. -See the [adapter](../../packages/provider-pi/src/server/adapter.ts). - -Antigravity separates account profiles per instance while sharing installed executables across the -environment. The 1.5 CLI keeps every profile's sign-in in one OS keyring entry and ignores -`AGY_ACP_FORCE_FILE_STORAGE`; only its SSH-session check stores the sign-in in the profile, so Google -account instances launch with `SSH_CONNECTION` set and sign in with `--login`. Gemini Enterprise -has no such sign-in and still shares the keyring entry. The launch environment removes ambient Google credentials, -so an instance cannot silently use another account or billing project. The agent also resolves -its user-global skill directories under that profile, so the profile links those two directories -back to the user's real `~/.gemini`; MCP servers, hooks, and rules there stay out of the profile. -See [profile isolation](../../apps/server/src/provider/antigravityAuthSupport.ts). - -The [Antigravity installer](../../apps/server/src/provider/AntigravityInstallation.ts) outlives -client connections and provider-instance rebuilds. Releases are immutable, with an atomic pointer -selecting the version for new processes. Running processes hold leases on their version. Updates -and removal must respect those leases instead of replacing executables under a running agent. - -A fixed MCP tool schema does not reach every stored Antigravity conversation. Before a turn in a -long conversation, `agy` runs context summarization with the tool declarations stored with that -conversation's last generation, not with the live MCP tool list. Only the last `gen_metadata` row of -`conversations/.db` in the agent's app folder holds the full request; `agy` shrinks the earlier -rows when it stores a new one. If that row declares a schema Gemini rejects, every later turn fails -with the same 400, logged by `agy` as `pre-invocation hook: context summarization:`, and stores no -new generation, so the conversation never recovers. A short conversation recovers on its next turn, -which skips summarization. While no turn can start on the thread, a SQLite `.backup` of the file and -then deleting that one row heals it, however many turns failed; the transcript in `steps` stays. -Keep advertised schemas within what Gemini accepts, as [the advertised schema -transform](../../apps/server/src/mcp/advertisedJsonSchema.ts) does. - -## Setup must not happen as a health-check side effect - -Opening a provider session can start MCP servers, run hooks, or launch a login browser. -[Grok probes](../../packages/provider-grok/src/server/status.ts) avoid authentication and -session creation for this reason. Antigravity likewise reserves authenticated catalog sessions for -explicit setup or model refresh; background checks use initialization only. - -[Antigravity sign-in](../../apps/server/src/provider/AntigravityAuth.ts) belongs to the initiating -T3 auth session. The client carries the return URL back to the environment because the provider's -loopback listener may be on another machine. Forward only the callback for the owned pending flow; -a successful callback HTTP request is not proof that provider authentication finished. The native -process owns token exchange and storage. - -Managed ChatGPT sign-in for a remote environment can finish on a local primary. The -[primary handoff](../../apps/server/src/provider/CodexChatGptHandoff.ts) uses an ephemeral -credential store and the destination's environment ID. It exchanges and verifies the code before -transferring the issued client registration and tokens. Only the destination persists and refreshes -that session; retaining a primary refresh session would race refresh-token rotation. Without a local -primary, the client uses the remote callback completion flow. - -Antigravity sign-out closes admission to new processes and stops existing processes before clearing account -metadata. Otherwise a helper or resumed session could retain the old account. Cached model lists -do not establish current access, and an authoritative empty catalog must clear the old list. - -Antigravity text-generation helpers deny tool requests, but native hooks and MCP configuration can -run before the prompt. They reject profiles with such configuration before launch. Prompt -instructions and tool denial do not create a native sandbox. -See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts). - -## Provider updates run only through the owning installer - -A package manager runs only when the resolved executable's path proves it owns the install. Homebrew -and npm are proven by the real path (symlinks followed): a versioned keg or cask under -`brew --prefix`, or `/lib/node_modules//` (Windows: the shim beside `node_modules`). -Native installer layouts and the global directories of pnpm, Bun, Yarn, and Vite+ may match on -either the resolved path or its real target, since those installers place real files or their own -symlinks there. Volta is proven by the package's image directory plus either its `volta-shim` link -or, on Windows, the exact cmd or bash forwarding script Volta generates; a custom script that merely -calls `volta run` does not qualify. When nothing is proven, Pi's and Grok's own updaters -(`pi update --self`, `grok update`) run instead, because each detects its installer itself; the -runner's version check catches an updater that exits 0 without updating. Claude, Codex, and OpenCode updaters only act on their own native layout, so -those providers stay manual-only unless that layout is proven. Mise is checked -first, since a `mise x` wrapper can sit at a native installer's path, and `MISE_DATA_DIR` can put -installs anywhere, so `mise which` is asked whenever mise is on `PATH`. Each driver names its fixed -mise tool; mise must resolve the binary and list it in an active install of that tool requested as -`latest`, which gets `mise upgrade `. T3 Code keeps launching the configured path, so that -path must be a shim or under the tool's `latest` link, which the upgrade repoints: a version -directory (including one `mise activate` put on `PATH`) would keep running the old binary until mise -prunes it. Everything else mise touches (fixed version paths, pinned tools, wrappers, OpenCode 1.x, -whose mise tool crosses into 2.x) stays manual-only, so T3 Code never edits mise config. Nix store installs stay manual-only too, since the store is read-only. `mise latest` supplies the version, because settings such as -`minimum_release_age` can hold mise behind npm. A Grok cask whose Homebrew prefix -cannot be verified also stays manual-only: `grok update` would install a second copy. npm updates pin `--prefix` because the -`npm` on `PATH` can belong to a different Node than the one that owns the provider. Homebrew -compares against `brew info` since casks trail npm by hours; native installs share npm's version -train, so the registry stays authoritative for them. A Chocolatey install of Claude stays -manual-only: its package directory is writable only by administrators, and `claude update` through -the shim installs a native copy elsewhere. The latest version comes from `choco search`, and the -card shows `choco upgrade claude-code` without running it. -See the [resolver](../../apps/server/src/provider/providerMaintenanceRunner.ts). - -Ownership is cached per instance and re-read immediately before an update runs. The -[runner](../../apps/server/src/provider/providerMaintenanceRunner.ts) refuses when the lock key -changed since the advisory, and reports success only when the refreshed provider is still installed -with a readable, current version. - -## Protocol traps - -Codex async questions arrive as notifications and are answered with a new user message. There is -no pending RPC response to send. The -[adapter](../../apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts) persists them as -`user_input_request` turn items and runtime requests with `responseCapability: { type: "message" }`. -Their execution nodes do not block the run. Web, desktop, and mobile use their normal question -panels, and requests remain pending after a turn finishes, a provider exits, or the server restarts. - -`runtime-request.respond` reads the persisted request and question item, validates required -answers, and commits the resolution and a user message in one transaction. Repeating the same -command returns its receipt without posting the answer twice. The normal message path starts or -resumes a run, queues behind active work, or steers when the adapter supports it. Blocking questions -retain the provider's live response path. Do not infer that a request has disappeared merely because -it is outside the recent history window. - -Native `/goal` state belongs to the provider and is mirrored on the provider thread. Codex starts -the next goal turn on its own milliseconds after the last one completes, so the -[adapter](../../apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts) keeps the run open -and adds that turn to it. One run can therefore own several native turns. `/goal` commands that -start no Codex turn settle on a provider turn without a native ref, which native rollback must -not count. Claude's SDK mode emits no goal events; its adapter reads goal state from the -synthetic command output and Stop hook feedback in the transcript. - -Capabilities must describe what the provider can actually do. Antigravity can capture workspace -checkpoints but cannot roll back its conversation. The [checkpoint boundary](./overview.md#turn-completion-and-checkpoints) -therefore rejects revert before touching files. Native permission and question option IDs must -also survive normalization; a display label is not necessarily a valid reply. - -## Attachments and stored history - -Attachments live outside the project workspace. The -[attachment boundary](../../apps/server/src/orchestration-v2/AttachmentClaims.ts) validates and claims -uploads for a thread; adapters choose native input formats for those environment-local files. -A path in the prompt does not grant filesystem access. Keep provider sandbox and approval rules -in force; copying uploads into the project to bypass them changes that boundary. - -File attachments introduced a replay compatibility limit. Image-only clients cannot decode -file-bearing messages, and an image-only server can fail the entire environment's startup when -replaying one such event. Rollouts and downgrades must account for persisted history as well as -current client support. - -## Provider diagnostics - -Native event logs retain lifecycle events, responses, and failures. Token deltas and duplicate raw -frames are filtered before adapters copy or redact payloads. The filter accepts both legacy native -events and v2 protocol envelopes; decode failures remain visible through diagnostic frames. - -Log payloads have a 64 KiB encoded budget. Large or deeply nested payloads become structural -summaries that retain routing identifiers, methods, status, and error fields. Traversal is bounded -before redaction and serialization, so logging a large response does not require several full -copies. These limits apply to diagnostics; provider event handling is unchanged. - -Codex resumes with metadata-only reads when it needs a thread's identity and update time. Its -initialization capabilities opt out of `turn/diff/updated`: T3 derives diffs from checkpoints. -The logger filters those notifications before traversal when an older provider still sends them. - -Model classification has its own [manifest constraints](./model-manifest.md). Assistant-reference -handling is documented under [citations](./assistant-citations.md). diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md deleted file mode 100644 index 0608c08a35c8b..0000000000000 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ /dev/null @@ -1,659 +0,0 @@ -# Orchestrator MCP Server - -## Purpose - -T3 exposes V2 orchestration through its app-owned MCP endpoint. A provider -agent can use this endpoint to: - -- create an app-owned sub-agent on any supported provider instance; -- wait for or poll the sub-agent's durable result; -- cancel an active delegated task; and -- create one or more ordinary top-level T3 threads; -- list a project's threads and incrementally read any thread; -- rename threads, regenerate titles, and link or unlink pull requests; -- send or steer follow-up messages; -- wait for or interrupt ordinary thread runs; and -- schedule recurring work that runs without an active turn. - -These are T3 orchestration operations, not provider-native sub-agent APIs. -Delegated tasks always create a T3 child thread and run. The child receives -only the supplied task prompt, plus an optional role instruction supplied in -the same tool call. Parent conversation history is not copied into the child. - -`ThreadManagementService` is the shared server application boundary for V2 -WebSocket commands and MCP. It owns thread lookup, listing, send-mode -selection, durable send postconditions, wait polling, and interrupt selection; -`OrchestratorV2` remains the lower-level command/event processor. Transport -adapters only authenticate, resolve transport-specific inputs, and shape -responses. - -## Transport And Authentication - -The orchestration tools share the existing authenticated HTTP MCP endpoint: - -```text -http://127.0.0.1:/mcp -``` - -The provider-visible server key is `t3-code`. The endpoint registers both the -preview toolkit and the orchestration toolkit. - -Before `ProviderSessionManager` opens a new V2 provider session, it asks -`McpSessionRegistry` for a credential scoped to: - -- the T3 environment; -- the parent T3 thread; -- the concrete provider instance; and -- the provider session. - -The credential grants `preview` and `orchestration` capabilities. Credentials -expire after a maximum lifetime, expire when idle, and are revoked when the -provider session is released. The raw token is not persisted in orchestration -state. - -The MCP HTTP server resolves the bearer token and supplies the resulting -`McpInvocationScope` to tool handlers. Orchestration handlers additionally -check the `orchestration` capability before reading or mutating state. - -## Provider Injection - -### Codex V2 - -Codex gets T3's MCP server in each thread's `thread/start`, `thread/resume`, -and `thread/fork` config, with the provider-session token in an -`Authorization` header. The same server is registered twice: - -- `t3-code`: every tool except `t3_thread_wait` and `delegate_task`. -- `t3-code-direct`: only `t3_thread_wait` and `delegate_task`, with - `omit_tools_from = ["code_mode", "deferred"]`. - -Code Mode yields a script after about 30 seconds, so the model polls a blocking -`t3_thread_wait` or `delegate_task` with `mode: "wait"`, resending its context -on each poll. The second entry makes both direct tool calls, like Codex's own -wait tools. Codex reports calls as `.`, so -`packages/shared/src/t3McpToolPresentation.ts` must resolve both server names. -Tool display and pending-work detection depend on it. - -### Claude Agent SDK V2 - -Claude receives an HTTP MCP server in its query options: - -```ts -{ - mcpServers: { - "t3-code": { - type: "http", - url: "http://127.0.0.1:/mcp", - headers: { - Authorization: "Bearer ", - }, - }, - }, - allowedTools: [ - // existing allowed tools - "mcp__t3-code__*", - ], -} -``` - -The adapter logs only whether MCP configuration exists; it does not log the -server headers or token. - -### Cursor Agent SDK V2 - -Cursor receives the same authenticated HTTP MCP endpoint through the SDK's -`mcpServers` on `Agent.create` / `Agent.resume` and each `send`. With -`@cursor/sdk` 1.0.39+, send-level servers replace only the create-time inline -set; ambient servers from `settingSources` (`project`, `user`, `team`, `mdm`, -`plugins`) stay available. The adapter passes the authorization header to the -SDK but projects only redacted option metadata into protocol diagnostics. - -### Grok ACP V2 - -Grok receives the authenticated HTTP MCP endpoint through the ACP -`session/new`, `session/load`, and `session/fork` `mcpServers` field. The shared -ACP adapter owns standard protocol behavior; the Grok flavor adds xAI extension -requests such as structured user questions. - -ACP does not define native subagents or active steering. Grok therefore uses -orchestrator-owned child threads and implements steering through -cancel-and-restart. Its current driver also lacks `session/fork`, so app forks -use portable context transfer. These are orchestrator policies, not -provider-specific MCP tools. - -### ACP Registry V2 - -The `acpRegistry` driver is the generic flavor of the same shared ACP adapter. -Each provider instance names an agent from the official ACP Registry. Settings -searches the registry through the connected server, then prepares a compatible -distribution before persisting the provider instance. Binary distributions use -a managed, versioned cache; declared checksums are verified when present. -Version-pinned `npx` packages install globally through `npm`; `uvx` packages use -`uv tool install`. ACP launches the resulting global command directly, so the -same command is available for terminal authentication. A local executable may -override the installed command without changing the registry-declared arguments -or environment. - -Search, preparation, provider status, and session startup share one -server-scoped catalog service. This keeps platform selection and registry -validation identical across settings and runtime use. Catalog inspection never -starts an ACP process, probes models, or performs authentication. The managed -provider snapshot creates a disposable `session/new` through the normal provider -refresh lifecycle, using success as the authentication-readiness proof and -projecting advertised models into the snapshot. Terminal-only login remains a -manual operation on the connected server. - -Capabilities such as session loading, session forking, models, modes, and MCP -transport are enabled only when the selected agent advertises them. Missing -features degrade through V2 policy: steering uses interrupt-and-restart, -forking uses portable context when native `session/fork` is unavailable, and -subagents use orchestrator-owned child threads. Registry agents do not receive -provider-specific extensions; those remain in flavors such as Grok. - -### Pi V2 - -T3 keeps a provider-session HTTP bridge even when Pi supports native MCP. -`mcp.json` entries override native registrations, and native MCP's default -60-second request timeout can interrupt long-running T3 tools. The bridge owns -the injected endpoint and credential and forwards Pi's cancellation signal. - -When a provider session credential exists, the adapter writes a T3-owned -extension into the server cache and spawns -`pi --mode rpc --extension /pi-t3-mcp-extension.ts` with: - -```text -T3_MCP_URL=http://127.0.0.1:/mcp -T3_MCP_BEARER_TOKEN= -``` - -The extension preserves public names under `mcp__t3-code__` for saved loadouts -and tool selectors. Modern Pi also receives `mcp__t3_code__` aliases, Pi's own -name for the server, which reserve it against configured MCP servers. They are -`model-only` and hide their own declarations, so the model can call them without -added declarations, search results, or codemode entries. An alias follows its -public tool: dropped when that tool is excluded, and off while a direct one is -off. Pi's `hidden` exposure would make them unreachable. On Pi 0.99+, -`orchestrator_capabilities`, `delegate_task`, and `task_status` remain directly -available; optional tools are discovered through Pi's builtin `tool_search`. -On older Pi or without builtin search, all tools remain directly available. -The bridge calls the original MCP tool name over HTTP. Follow-up requests send -`mcp-protocol-version: 2025-06-18`; Effect's MCP transport returns 400 -without it. The first turn of a session also receives the shared T3 -orchestration instructions. - -Pi keeps ownership of native extension discovery. T3 does not replace Pi's -`subagent` tool or reproduce Pi's package and project-trust loader. Durable -delegation goes through the namespaced T3 MCP `delegate_task` tool and the -shared orchestration child-thread lifecycle. When Pi's example `subagent` -extension is installed, the adapter observes its documented `details.results` -shape and projects task cards with no child thread id. Unknown result shapes -remain ordinary dynamic tool output. - -### Provider Support - -A provider instance can run child tasks when its live `ProviderInstance` -exposes a V2 `orchestrationAdapter` — the same registration the orchestrator -resolves when a `delegated_task.request` executes. That covers Codex, Claude -Agent SDK, Cursor Agent SDK, Grok, generic registry agents over ACP, OpenCode, -OpenCode 2, Pi, Antigravity, and any future driver that builds an adapter. -Capability discovery still reports other registered provider instances, but -marks them unavailable for orchestration when no adapter resolves. This keeps -provider selection model-visible without allowing a request that cannot run. - -## Tool Surface - -`OrchestratorToolkit` in -[`toolkits/orchestrator/tools.ts`](../../apps/server/src/mcp/toolkits/orchestrator/tools.ts) -is the authoritative list of orchestration tools. The sections below cover -delegation and thread tools. `t3_thread_launch` is documented with them but -registered by the project toolkit in -[`toolkits/project/tools.ts`](../../apps/server/src/mcp/toolkits/project/tools.ts). - -### `orchestrator_capabilities` - -Returns: - -- the inherited provider instance and model; -- the parent runtime and interaction modes; -- registered provider instances and advertised models; -- whether each provider can run a child task; and -- feature flags for polling, cancellation, and batch thread creation. - -Unavailable providers include model-visible constraints such as missing V2 -adapter support, disabled state, missing executable, or missing authentication. - -The model list is short on purpose: catalogs such as OpenCode can hold hundreds -of models, and every call lands in the agent's context. Each provider lists -custom, favorite, and the caller's own models, plus all current (non-legacy) -models for Codex, Claude, Muse, and Grok, or the first 8 current models in the -user's model order for other providers. `omittedModels` counts the rest, and the -`search` input finds them, legacy models included. `delegate_task` still accepts -any catalog model. - -### `delegate_task` - -Creates a T3-owned child thread and immediately dispatches the supplied task -prompt. - -The [shared contract](../../packages/contracts/src/orchestratorMcp.ts) is authoritative for -inputs and results, including target options and linked-environment fields. - -```ts -import type { - OrchestratorMcpDelegateTaskInput as DelegateTaskInput, - OrchestratorMcpDelegateTaskResult as DelegateTaskResult, -} from "@t3tools/contracts"; -``` - -For local delegation, provider, model, runtime mode, and interaction mode inherit -from the parent when omitted. A driver-only target inherits the parent's provider instance -when it can run child tasks, and otherwise selects an available instance of -that driver; an explicit `providerInstanceId` is honored exactly and fails -when unavailable. Selecting a different provider without a model uses that -provider's first advertised model. - -Set `target.options` using the options returned by `orchestrator_capabilities`, such as -`{effort: "max"}`. Supplied values override inherited selections; `{}` or `[]` clears them. -For local delegation, use `isolation: "worktree"` for a separate prepared checkout from -the parent's commit; the default `"shared"` uses the parent's checkout. Uncommitted parent -edits are not copied. A linked-environment target (`target.environmentId`) runs in the remote -project's checkout and rejects worktree isolation. To launch an isolated thread there, use -`t3_thread_launch` with `environmentId` and a worktree `workspaceStrategy`. - -A provider runs a runtime mode it does not offer as `approval-required`, so a -child would ask for approval on every command. `orchestrator_capabilities` -lists `runtimeModes` only for a provider that offers some of the modes, and -omits it for a provider that offers all of them. When the target lists -`runtimeModes`, an explicit `runtimeMode` outside that list is refused, and an -inherited mode steps down to the broadest mode the target offers. - -Each independent delegated review round uses a new `delegate_task` call with the -original brief, prior findings, responses, and unresolved objections. Track each -round by its own `taskId` and use a distinct `clientRequestId` per round, stable -across retries of that round. -A follow-up that needs the same child's conversation goes through `t3_thread_send` -on its `childThreadId`. After the original task completes, that follow-up runs as a -fresh task in the child thread; it does not reopen the completed task or change its -published result. - -Delegation requires an active parent run owned by the MCP credential's -provider session. The request becomes the V2 command -`delegated_task.request`. - -`mode: "async"` returns the current durable state immediately. -`mode: "wait"` waits for the task result, including nested work and completion follow-ups, or until -the timeout expires. A wait timeout does not cancel the child; the result sets -`waitTimedOut: true`. When the result includes `next`, completion wakes the parent: -do not wait on the task or poll it; continue other work, and end the turn when none is -left. A pending blocking question also ends the wait with `hasPendingQuestion: true` and -`waitTimedOut: false`. -If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request` with -action `list`, `read` (with `requestId`), or `respond`, or ask the user; the task's completion still wakes this thread. A pending live approval for the -task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`; -it grants no approval authority. Read the fresh full request in the child thread before -responding, since the durable record can outlive its provider callback. Async questions -do not end the wait. - -### `task_status` - -Reads a delegated task from the parent thread's durable projection. A task ID -from another parent thread is rejected. `childRunId` identifies the original -run. `status: "starting"` means the child's provider has not started its turn -yet, so a task that stays there has not begun work. A task in a linked -environment reads its run's status there for this. `workState` distinguishes -active work, a finished turn waiting for children, and an available result. The -task remains nonterminal until its known work finishes. Its published `summary` -and result transfer then remain stable across later follow-ups. -`hasPendingChildRuns` reports later queued or executing turns; `latestTerminal*` -exposes later executed, non-monitor results without replacing the published task -result. - -### `task_cancel` - -Stops every task the child delegated, then the child thread with the internal -`thread.stop` command, cancels the task's own queued turn, and disposes automatic -parent delivery. Like a user Stop, `thread.stop` interrupts the running turn, holds -queued turns, and ends pull request watches. The task's own queued turn is cancelled -even if Stop already held it, so a task that is only queued can be cancelled; other -queued turns in the child stay held for Resume. A nonterminal task is rejected when -it has no interruptible run, no queued turn of its own, and its finished turn no -longer waits on background work or delegated tasks. Once a cancelled task's turn -ends, a completed result settles as `interrupted` and a failed one stays `failed`. A -terminal task returns its existing status, and its child thread still stops, -including later runs and watch wakes. In both cases, a follow-up that lost its child -run but still shows as running on the parent is cancelled there and reported as -`cancelled`. Published task results remain available. It accepts an -optional cancellation reason. - -### `create_threads` - -Creates between one and twenty ordinary top-level T3 threads: - -```ts -import type { OrchestratorMcpCreateThreadsInput as CreateThreadsInput } from "@t3tools/contracts"; -``` - -Each entry independently resolves provider, model, and modes. The new threads -inherit the parent's project, branch, and worktree path, but they have no -sub-agent lineage. Entries with a prompt immediately dispatch a run; entries -without a prompt remain idle. `create_threads` is local-only: `target.environmentId` and -`target.projectId` are ignored even though the shared target contract accepts them. Use -`t3_thread_launch` with `environmentId` and `projectId` to select another environment or project. - -### `t3_thread_launch` - -Launches one ordinary top-level thread through the app's launch service. Use an -explicit `workspaceStrategy` to create a new worktree (`worktree` with `baseRef`), -attach an existing checkout (`existing_worktree` with `worktreePath`), or use the -project root (`root`, also the default). The thread is bound to that workspace -before the agent starts. Creating a worktree in the task prompt does not update -this binding. - -Pass the task in `message`. Project, model, and modes inherit when omitted; -workspace does not. `scratch: true` launches without a project, in a folder of -its own under the environment's Scratch project. A new worktree with `startFromOrigin` omitted follows the new-worktree setting. For stacked PRs, use the parent branch as `baseRef` with -`startFromOrigin: false`. The new thread may not run with broader runtime or -interaction modes than the caller. As for `delegate_task`, a runtime mode the -provider does not offer is refused, and an inherited or default one steps down -to the broadest mode it offers. `create_threads` remains the batch option for a -shared checkout. - -Set `clientRequestId` on the initial launch to make it retryable. After an error -or a lost reply, resend the same request with the same key from the same -provider session. This reuses any thread already created by that request. If the -initial request had no key, check for the thread before launching again. - -### `t3_thread_list` - -Lists durable thread shells in one project, newest first: `projectId` when -given, else the calling thread's project. Callers can filter by title, run -status, and whether app-owned sub-agent threads are included. Results are -bounded and offset-paginated. Deleted threads are never listed. - -### `t3_thread_read` - -Reads the durable state, recent runs, and visible timeline of any thread in -the environment by thread ID. A deleted thread returns `thread_not_found`. The -default `messages` view returns user messages, assistant -messages, and proposed plans. The `activity` view also returns summarized tool, -reasoning, checkpoint, handoff, and runtime-request items. Large item text is -bounded and reports whether it was truncated. An agent in a T3 thread that -reads without a cursor gets the newest items, and `beforePosition=earlierPosition` -reads older ones. Client callers (the CLI, linked environments, outside MCP -clients) start at the oldest item instead, because the CLI and linked -environments on older versions read that way and follow only `hasMore`. -`afterPosition=-1` starts any read at the oldest item, and -`afterPosition=nextPosition` reads newer items. The server stops adding items once the result reaches about 30,000 characters and -reports the rest through `earlierPosition` or `hasMore`. Claude Code saves MCP -results over its token limit to a file instead of showing them, so a read has -to fit whatever `limit` an agent asks for. - -Thread and message results include required `createdBy` and `creationSource` -provenance. MCP-created threads and user-role messages use `createdBy: "agent"` -and `creationSource: "mcp"`; provider output uses `creationSource: "provider"`. -Actor and ingress are separate so agent-authored user-role messages remain -distinguishable from human-authored messages. - -Agents mention another thread by the `link` its result carries, -`/>`, so they never format an id or -write a title, which goes stale when the user renames the thread. The -environment that owns the thread builds the link, so forwarded results and tasks -delegated to a linked environment name that environment. Clients open only that -environment's thread and show its current title; a link to a thread they do not -know renders as a label that opens nothing. Older `t3-thread://v1/` -links name no environment: clients resolve them in the message's environment, -then by a unique match in another enabled environment. An outside OAuth client, -one that is not a linked environment, cannot render `t3-thread://` links, so it -gets the link Copy thread copies, `https://app.t3.codes/threads//` -on the server's `T3CODE_HOSTED_APP_URL`, for threads in this environment. The -hosted app offers the desktop app, the mobile app, or itself. - -List and read results report `snoozed`, `snoozedUntil`, and `pinned`, and -`t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows the -client's `effectiveSnoozed`, so agents and the sidebar agree: a snoozed thread -wakes early only when it has a pending request or fails after snoozing. Completed -runs, background wakes, and delegated completions keep it snoozed. - -They also report `blockedOnThreadWait` and `pendingBackgroundTasks`, the shell -fields behind the sidebar's Waiting label, so an agent can see what a thread -still waits on after its run completed. A subagent or `background_task` holds -the thread. A command or monitor holds it only with `awaited: true`, since agents -often leave a dev server running. - -### `t3_thread_update` - -Updates metadata for the calling thread or any other thread in the environment. -The typed actions are `rename`, which requires `title`, and `regenerate_title`, -which rejects one. Pull request links go through the separate -`link_pull_request` and `unlink_pull_request` tools. Branch and workspace -changes are outside this tool. - -The result includes the command ID and durable event sequence together with the -resultant title, title-regeneration marker, and linked pull request. Reusing a -`clientRequestId` for the same action and thread replays the same command -receipt. Thread list and read results expose the linked pull request, and thread -detail also exposes an in-flight title regeneration. - -### `t3_thread_send` - -Sends a message to any ordinary or delegated thread in the environment: - -- `auto` starts an idle thread, steers a fully active turn, or queues behind a - turn that is not yet steerable; -- `queue` creates a separate follow-up run after active work; -- `steer` requires a steerable active provider turn; -- `restart` requires an active provider turn and uses the orchestrator's - interrupt-and-restart path. On a provider that can stop a turn and queue - messages but not restart a turn with new input, it stops the turn and queues - the message ahead of other queued messages; an unheld delegated-task result - that survives the stop still runs first. It is rejected when neither path - applies: the provider cannot stop a turn, Stop has already reached the turn, - or the turn or the new message is `/compact` or `/logout`; and -- `fyi` starts no turn and returns `delivery: "held"` with no run. The - thread's next turn start adds the waiting FYI messages to that turn's input, - and a running Claude Code turn also gets them as context once its tool calls - resolve, before its next model request. An FYI counts as delivered only when - the turn that carries it completes; a turn that fails, is interrupted, - restarts or is rolled back gives it back, so the agent may see it twice. A - thread with a waiting FYI gets a quiet wake turn once it has been idle 6 - hours, counted from the latest of its creation, its runs' last activity, and - the reset of a usage limit that failed its latest run on the provider the - thread still uses (or that limit's snooze end, when later), and not before - its snooze ends. No wake reaches a thread that is settled or archived, has a - run that has not ended (a queued one included), has a runtime request that - waits for an answer, or whose provider is disabled. A wake carries waiting - FYIs up to the 16,000-character turn budget; FYIs it does not carry, or gives - back because it failed or was stopped, get another wake after 6 more idle - hours. `fyi` with `freshContext`, or with more than 16,000 characters, is - rejected. `t3_thread_read` marks each FYI item `fyi: "waiting"`, `"sent"`, - `"delivered"`, or `"unknown"` when its run cannot be found. - -The target runtime and interaction modes may not be broader than the caller's. -Stable command and message IDs are derived from `clientRequestId` for -idempotent retries. - -`outputSchema` (also on `t3_thread_launch`) asks the run for a result as data. -The run stores the schema, the turn's prompt ends with how to hand the result -back, and the agent calls `t3_submit_output`. The server checks the value -against the schema before storing it, so the caller never parses a reply. A send -that asks for a result is queued instead of steered: the result belongs to one -whole turn. A turn can end without submitting; the caller sees a finished run -with no `output`. - -### `t3_submit_output` - -Stores the calling thread's result on its running turn, once it fits the schema -that turn was sent with. A turn that was asked for nothing answers for the -newest turn that was asked and has not answered yet, which is how an agent that -ended its turn to wait gives its result after it is woken. A rejection names what did not fit, so the agent can -correct it and call again; a later accepted submission replaces an earlier one. - -### `t3_thread_wait` - -Waits for a selected run to become `completed`, `failed`, `cancelled`, -`interrupted`, or `rolled_back`. Without `runId`, it pins the latest run at call -time; an idle thread returns immediately. A timeout reports the latest durable -status and does not cancel work. `output` carries what the run submitted -against its `outputSchema`; with `untilOutput`, a completed run that has not -submitted yet is waited on until it has. - -### `t3_workflow` - -Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and -lists the questions runs ask a person. It is advertised to clients outside a thread only, such as -the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows -through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. - -### `t3_thread_interrupt` - -Interrupts a selected active run through the normal V2 `run.interrupt` command. -Without `runId`, it selects the newest interruptible run. A terminal run is -returned unchanged, and a thread with no active provider turn returns -`no_active_run`. - -### Scheduled tasks - -`schedule_task`, `list_scheduled_tasks`, and `delete_scheduled_task` manage -recurring work in the app scheduler; `schedule_task` with a `scheduledTaskId` -updates an existing task. A schedule -runs its prompt on an interval, at a fixed time in the server's local time -zone, or on each qualifying webhook request, even when no turn is active. -Without a signature, anyone with the webhook URL can trigger a run. -Signature checks, filters, and dedupe can skip a webhook request. -`bindToCurrentThread` defaults to `true` only when the caller has a thread in -the task's project; otherwise it defaults to `false`. Bound runs post into -that thread; unbound runs each launch a fresh thread in the task's project. -Explicit `bindToCurrentThread: true` without a caller thread in that project -is rejected. Pausing uses `schedule_task` with `scheduledTaskId` and `enabled: false`; -deletion is permanent. - -## Delegated Task Lifecycle - -The MCP server is a command ingress into V2. It does not call provider adapters -directly. - -```text -provider model - -> MCP tools/call delegate_task - -> authenticated OrchestratorMcpService - -> shared ThreadManagementService - -> V2 delegated_task.request command - -> child thread + child run - -> parent app_owned subagent projection - -> parent/child execution nodes - -> consumed subagent_spawn context transfer - -> normal provider effect and runtime ingestion - -> child run reaches a terminal state - -> parent subagent/node/turn item finalized - -> consumed subagent_result context transfer - -> wait result or later task_status result -``` - -The child thread has lineage relationship `subagent` and points back to the -parent node. The parent gets an `app_owned` sub-agent projection and a -sub-agent turn item so the existing debug UI can render progress. - -Terminal provider events trigger finalization. The event stream first replays -persisted events and then follows live events, so finalization also runs after -a server restart. An existing `subagent_result` transfer makes finalization -idempotent. - -Users rarely watch child threads, so a child question would otherwise go -unanswered. When a child opens a pending `user_input` request, the parent gets -a notification message telling it to answer with the pending request tools or -ask the user. The message says whether the child is blocked or, for a Codex -async question, still working. If the parent's turn is running and its provider -can steer without interrupting tools, the notification steers into that turn, -like a background task's completion. A queued notice would wait behind a -long-running orchestrator turn that may never end. Otherwise it queues. If the -question is answered or dismissed before a queued notification starts a turn, -that queued turn is cancelled. Approvals are not -routed, because those tools cannot answer them. -A parent still blocked in a `delegate_task` wait gets the blocking question -through that wait instead. -If the provider cuts that wait short, a still-pending live question wakes the -parent when its launching run completes, fails, or waits for post-turn work. -Stopping or interrupting the parent prevents this catch-up. - -A failed run exposes its provider error before any progress text. Successful -results use the latest assistant content from the final work turn. - -## Policy And Idempotency - -- A child runtime mode may stay equal to or become narrower than the parent - mode. It may not escalate privileges. -- A child interaction mode may stay equal to or narrow from `default` to - `plan`. It may not escalate from `plan` to `default`. -- Thread tools take any thread in the environment as a target. For a thread - caller, list and search cover one project: its own unless `projectId` is given. -- A tool that changes another thread needs the calling thread's live run, and - the target's runtime and interaction modes may not be broader than the - caller's. This is the same privilege ceiling as child creation. -- Provider instances must be enabled, installed, available, authenticated, and - backed by a V2 adapter. -- A requested model must be advertised by the selected provider when the - provider publishes a model list. -- `clientRequestId` derives stable command, thread, and message IDs within the - provider session. Retrying the same call returns the same durable work. -- Calls without `clientRequestId` receive a generated request key and create - new work. - -Expected denials use the typed `OrchestratorMcpFailure` result: - -```text -capability_denied -parent_not_active -provider_unavailable -model_unavailable -runtime_mode_escalation_denied -interaction_mode_escalation_denied -task_not_found -task_not_cancellable -thread_not_found -run_not_found -thread_not_sendable -thread_not_interruptible -invalid_request -orchestration_error -``` - -## Code Ownership - -- Shared schemas: `packages/contracts/src/orchestratorMcp.ts` and - `packages/contracts/src/threadMetadataMcp.ts` -- MCP services: `apps/server/src/mcp/OrchestratorMcpService.ts` and the focused - `apps/server/src/mcp/ThreadMetadataMcpService.ts` -- Tool definitions and handlers: - `apps/server/src/mcp/toolkits/orchestrator/` -- HTTP registration and authentication: - `apps/server/src/mcp/McpHttpServer.ts` -- Credential lifecycle: `apps/server/src/mcp/McpSessionRegistry.ts` -- Provider injection: - `apps/server/src/orchestration-v2/ProviderSessionManager.ts` and V2 adapters -- Durable delegated-task command and finalization: - `apps/server/src/orchestration-v2/Orchestrator.ts` - -## Verification - -The integration test uses the real MCP toolkit registration, V2 orchestrator, -SQL persistence, event ingestion, projections, and checkpoints. Only the -external provider adapters are deterministic test implementations. - -Coverage includes: - -- capability discovery; -- cross-provider delegated completion; -- prompt-only child context; -- parent and child lineage projections; -- spawn and result context transfers; -- async status polling; -- cancellation; -- batch ordinary-thread creation; -- thread listing and timeline reads, including another project's threads; -- ordinary-thread send, wait, steering, and interruption; -- inheritance and per-thread provider overrides; and -- idempotent retries. - -Provider adapter tests separately verify Codex, Claude, Cursor, Grok, and ACP -Registry behavior and MCP injection. The provider-session manager test verifies -that credentials exist before an adapter opens and are revoked when it closes. diff --git a/fork/docs/internals.md b/fork/docs/internals.md new file mode 100644 index 0000000000000..057fde866b37a --- /dev/null +++ b/fork/docs/internals.md @@ -0,0 +1,66 @@ +# Fork internals + +These notes document internals of changes this fork carries on top of upstream T3 Code. + +## Outbox order and long timers + +A thread's effects run in outbox order. A pending effect blocks every later effect of its thread, +even when its `available_at` time is hours away. Title generation has its own lane. Use a +[Scheduler](../../apps/server/src/scheduling/Scheduler.ts) sweep for a long timer, as in +[UsageLimitRecoveryWorker](../../apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts), not +a delayed outbox effect. + +## Antigravity context summarization + +A fixed MCP tool schema does not reach every stored Antigravity conversation. Before a turn in a +long conversation, `agy` runs context summarization with the tool declarations stored with that +conversation's last generation, not with the live MCP tool list. + +Only the last `gen_metadata` row of `conversations/.db` in the agent's app folder holds the full +request. When `agy` stores a new row, it shrinks the earlier rows. If that last row declares a +schema that Gemini rejects, every later turn fails with the same 400 error. `agy` logs the failure +as `pre-invocation hook: context summarization:`. Because the failed turn stores no new generation, +the conversation never recovers. A short conversation skips summarization and recovers on its next +turn. + +While no turn can start on the thread, take a SQLite `.backup` of `conversations/.db` and delete +that last `gen_metadata` row. Deleting that one row heals the conversation no matter how many turns +failed, and the transcript in `steps` stays. + +Keep advertised schemas within what Gemini accepts, as +[the advertised schema transform](../../apps/server/src/mcp/advertisedJsonSchema.ts) does. + +## The `fyi` mode of `t3_thread_send` + +The `fyi` mode of `t3_thread_send` starts no turn and returns `delivery: "held"` with no run. +`t3_thread_send` rejects `fyi` with `freshContext` or with more than 16,000 characters. + +When the thread starts its next turn, that turn adds the waiting FYI messages to its input. A +running Claude Code turn also receives waiting FYI messages as context after its tool calls resolve +and before its next model request. + +An FYI counts as delivered only when the turn that carries it completes. A turn that fails, is +interrupted, restarts, or is rolled back gives the FYI back, so the agent may see it twice. + +A thread with a waiting FYI gets a quiet wake turn after 6 idle hours. Idle time starts from the +latest of these timestamps: + +- the thread's creation, +- the last activity of its runs, and +- the reset of a usage limit that failed the thread's latest run on the provider the thread still + uses, or that limit's snooze end when later. + +A wake does not happen before the thread's snooze ends. No wake reaches a thread if any of these +conditions holds: + +- the thread is settled or archived, +- the thread has a run that has not ended, including a queued run, +- the thread has a runtime request that waits for an answer, or +- the thread's provider is disabled. + +A wake carries waiting FYIs up to the 16,000-character turn budget. Waiting FYIs that a wake does +not carry, or gives back because the wake failed or was stopped, get another wake after 6 more idle +hours. + +`t3_thread_read` marks each FYI item `fyi: "waiting"`, `"sent"`, `"delivered"`, or `"unknown"` when +its run cannot be found. diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ff0047faf8092..86623f3bfc31c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -4956,7 +4956,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } if (recoveredOutput !== undefined) { context.claimedToolResults.set(callInputKey, recoveredOutput); - output = recoveredOutput; + // Fork: an empty record (a Chat-mode send) adds nothing to what the provider reported. + if (Object.keys(recoveredOutput ?? {}).length > 0) output = recoveredOutput; } } }