From 0fcfc17c81a88eb5f0d9bff76425c5872f0465f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 11:39:06 -0800 Subject: [PATCH 001/190] fix(server): older history no longer reads every attempt row to find steered ones (#41620) --- apps/server/src/persistence/Migrations.ts | 2 ++ .../Migrations/111_SupersededRunAttemptIndex.ts | 14 ++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 2 ++ 3 files changed, 18 insertions(+) create mode 100644 apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 36762e9059b58..5c24577ad53ec 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -118,6 +118,7 @@ import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; import Migration0108 from "./Migrations/108_AgentFeedback.ts"; import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts"; import Migration0110 from "./Migrations/110_Workflows.ts"; +import Migration0111 from "./Migrations/111_SupersededRunAttemptIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -231,6 +232,7 @@ const migrationEntries = [ [108, "AgentFeedback", Migration0108], [109, "IssueTrackerAccounts", Migration0109], [110, "Workflows", Migration0110], + [111, "SupersededRunAttemptIndex", Migration0111], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts new file mode 100644 index 0000000000000..ad2f9f4a3817e --- /dev/null +++ b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Opening a thread's history looks up its few superseded attempts. Without this index that + // reads every attempt row of the thread, which is slow on a long thread with a cold cache. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_run_attempts_superseded_idx + ON orchestration_v2_projection_run_attempts(thread_id, run_id, root_node_id) + WHERE status = 'superseded' + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 1b8cf040b5fbc..de0d6a3f63ff5 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -90,6 +90,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -223,6 +224,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 4ab87289acdce039c9c68626f1fb74e8a3b59d50 Mon Sep 17 00:00:00 2001 From: James Cane Date: Mon, 23 Nov 2026 19:40:16 +0000 Subject: [PATCH 002/190] fix(server): recover dropped T3 MCP tool results in ACP and OpenCode Code Mode (#41552) Co-authored-by: Julius Marminge --- apps/server/src/mcp/McpHttpServer.ts | 74 +++- apps/server/src/mcp/toolkits/core.test.ts | 41 +++ .../Adapters/AntigravityAdapterV2.test.ts | 330 +++++++++++++++++- .../Adapters/OpenCode2AdapterV2.test.ts | 196 ++++++++++- .../provider/acp/AntigravityProtocol.test.ts | 34 ++ .../src/provider/acp/AntigravityProtocol.ts | 56 ++- packages/provider-acp/src/server/adapter.ts | 135 ++++++- .../src/server/McpProviderSessions.test.ts | 161 +++++++++ .../src/server/McpProviderSessions.ts | 153 +++++++- .../provider-opencode/src/server/toolItems.ts | 128 ++++++- .../src/server/v2/adapter.ts | 97 ++++- packages/shared/src/toolOutput.test.ts | 13 + packages/shared/src/toolOutput.ts | 20 ++ 13 files changed, 1398 insertions(+), 40 deletions(-) create mode 100644 packages/provider-core/src/server/McpProviderSessions.test.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index be41f8630b7dd..2b1deed86f037 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -56,6 +56,9 @@ import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; +import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -1218,6 +1221,67 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** + * ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on + * completion. Recording each thread-scoped call's compact result before returning lets adapters + * recover sent messages, IDs, counts, and error flags without depending on output passthrough. + */ +const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + if (Option.isNone(mcpSessions)) { + return yield* registration; + } + const capturingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + // html_render tracks its own path/hash recovery with publish cleanup in HtmlRender. + if (toolName === HTML_RENDER_TOOL_NAME) { + return server.addTool(options); + } + return server.addTool({ + ...options, + // Untraced: withToolSpans already opens a span per tool call. + handle: Effect.fnUntraced(function* (payload) { + const scopeOption = yield* Effect.serviceOption( + McpInvocationContext.McpInvocationContext, + ); + const thread = Option.getOrUndefined(scopeOption)?.thread; + const epoch = + thread === undefined + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + if (thread === undefined) return Effect.void; + if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) { + return Effect.void; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.void; + } + const output = + exit._tag === "Success" + ? compactT3McpToolOutput(toolName, exit.value) + : { isError: true }; + return output === undefined + ? Effect.void + : mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, { + providerSessionId: thread.providerSessionId, + epoch, + }); + }), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1300,8 +1364,10 @@ export const toolkitRegistration = , EX, ) => Layer.effectDiscard( withToolAnalytics( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolResultCapture( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( @@ -1318,7 +1384,7 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe( + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); @@ -1350,7 +1416,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); -const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); +export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 33c356af4e7e1..c1d35ace86940 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -416,6 +416,47 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); +it.effect("captures send_to_user results for providers that drop MCP outputs", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const draft = "### Status\n\nAll checks passed."; + const result = yield* server + .callTool({ name: "send_to_user", arguments: { message: 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( + undefined, + ); + + const invalid = yield* server + .callTool({ name: "send_to_user", arguments: { message: "" } }) + .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({ + isError: true, + }); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + ), + ), + ), +); + it.effect("records only failed calls of tools that hand off no work", () => { // Recording runs detached from the tool response, so the first event is awaited. const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..9924d6c831833 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,7 +13,12 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { + compactDynamicToolOutput, + htmlRenderFromToolItem, + previewRecordingIdFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -989,6 +994,329 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "recovers T3 MCP tool results across omitted outputs, replays, errors, and turn boundaries", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let promptIndex = 0; + let turn1Epoch = 0; + const instanceId = ProviderInstanceId.make("antigravity-mcp-result-test"); + const threadId = ThreadId.make("thread-antigravity-mcp-result"); + const statusUpdate = "### Current Status\n\nAll checks are passing."; + const inProgressText = "Streamed while running."; + const lateText = "Confirmed on a later completion."; + const lateErrorText = "Late explicit error."; + const unfinishedText = "Still running when turn ended."; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptIndex += 1; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const startTool = ( + toolCallId: string, + toolName: string, + rawInput: Record, + ) => + send({ + sessionUpdate: "tool_call", + toolCallId, + title: `Run mcp_t3-code_${toolName}`, + kind: "other", + status: "in_progress", + rawInput, + }); + const updateTool = ( + toolCallId: string, + status: "in_progress" | "completed" | "failed", + rawOutput?: unknown, + ) => + send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + ...(rawOutput === undefined ? {} : { rawOutput }), + }); + const recordSend = (message: string) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ); + + if (promptIndex === 2) { + // A Turn 1 handler finishing after Turn 1 closed must be rejected by epoch. + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: unfinishedText }, + { sentMessage: unfinishedText }, + { epoch: turn1Epoch }, + ); + yield* startTool("turn2-leaked-check", "send_to_user", { + message: unfinishedText, + }); + yield* updateTool("turn2-leaked-check", "completed", "Summary of turn 2"); + return { stopReason: "end_turn" as const }; + } + + turn1Epoch = yield* mcpSessions.toolResultEpoch(threadId); + + // agy 1.5.x adds toolSummary and omits output on completion, then may replay. + yield* startTool("send-empty", "send_to_user", { + message: statusUpdate, + toolSummary: "Send status update", + }); + yield* recordSend(statusUpdate); + yield* updateTool("send-empty", "completed"); + yield* updateTool("send-empty", "in_progress"); + yield* updateTool("send-empty", "completed", "Summary replay"); + + // Streaming output during in_progress still drains on completion. + yield* startTool("send-streaming", "send_to_user", { message: inProgressText }); + yield* recordSend(inProgressText); + yield* updateTool("send-streaming", "in_progress", { + sentMessage: inProgressText, + }); + yield* updateTool("send-streaming", "completed", { + sentMessage: inProgressText, + }); + yield* startTool("send-streaming-unpublished", "send_to_user", { + message: inProgressText, + }); + yield* updateTool("send-streaming-unpublished", "completed"); + + // Explicit MCP error preserves diagnostic content across summary replays. + yield* startTool("send-errored", "send_to_user", { message: "Denied" }); + yield* updateTool("send-errored", "completed", { + result: { + isError: true, + structuredContent: { sentMessage: "Denied" }, + content: [{ type: "text", text: "Denied by policy" }], + }, + }); + yield* updateTool("send-errored", "completed", "Summary of denied"); + + // Initial miss -> late explicit success or error still drains its new record. + yield* startTool("send-late", "send_to_user", { message: lateText }); + yield* updateTool("send-late", "completed"); + yield* recordSend(lateText); + yield* updateTool("send-late", "completed", { sentMessage: lateText }); + yield* startTool("send-late-unpublished", "send_to_user", { + message: lateText, + }); + yield* updateTool("send-late-unpublished", "completed"); + + yield* startTool("send-late-error", "send_to_user", { message: lateErrorText }); + yield* updateTool("send-late-error", "completed"); + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: lateErrorText }, + { isError: true }, + ); + yield* updateTool("send-late-error", "completed", { + result: { isError: true, content: [{ type: "text", text: "Denied late" }] }, + }); + yield* startTool("send-late-error-sibling", "send_to_user", { + message: lateErrorText, + }); + yield* updateTool("send-late-error-sibling", "completed"); + + // Empty-input completion that misses still recovers once a later completion brings arguments, + // and replacing arguments on the same call ID re-matches against the new arguments. + yield* startTool("send-late-args", "send_to_user", {}); + yield* recordSend("First args"); + yield* updateTool("send-late-args", "completed"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "First args" }, + }); + yield* recordSend("Second args"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "Second args" }, + rawOutput: "Summary of second", + }); + + // Bare failure without reported output must not consume a sibling call's cached result. + yield* startTool("send-bare-fail", "send_to_user", { message: "Shared ready" }); + yield* startTool("send-bare-fail-sibling", "send_to_user", { + message: "Shared ready", + }); + yield* recordSend("Shared ready"); + yield* updateTool("send-bare-fail", "failed"); + yield* updateTool("send-bare-fail-sibling", "completed"); + + // preview_recording_stop recovers its recording id. + yield* startTool("recording-stop", "preview_recording_stop", { + toolSummary: "Stop preview recording", + }); + yield* mcpSessions.recordToolResult( + threadId, + "preview_recording_stop", + {}, + { id: `${threadId}-rec-1` }, + ); + yield* updateTool("recording-stop", "completed"); + + // Unfinished call projected at turn end must not claim or leak to Turn 2. + yield* startTool("send-unfinished", "send_to_user", { + message: unfinishedText, + }); + yield* recordSend(unfinishedText); + + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-mcp-result"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + return Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + }); + const turn1Events = yield* runTurn(1); + const turn2Events = yield* runTurn(2); + const toolIn = (events: ReadonlyArray<(typeof turn1Events)[number]>, nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? event.turnItem + : undefined; + }; + const tool = (nativeId: string) => toolIn(turn1Events, nativeId); + + const sendEmptyUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-empty" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + sendEmptyUpdates.map((update) => sentMessageFromToolItem(update)), + [statusUpdate, statusUpdate], + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming")!), inProgressText); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming-unpublished")!), undefined); + const erroredUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-errored" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.strictEqual(erroredUpdates.length, 2); + for (const update of erroredUpdates) { + assert.strictEqual(compactDynamicToolOutput(update.output)?.isError, true); + assert.include(JSON.stringify(update.output), "Denied by policy"); + assert.strictEqual(sentMessageFromToolItem(update), undefined); + } + assert.strictEqual(sentMessageFromToolItem(tool("send-late")!), lateText); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-unpublished")!), undefined); + const lateErrorSibling = tool("send-late-error-sibling"); + assert.isDefined(lateErrorSibling); + assert.strictEqual(lateErrorSibling.status, "completed"); + assert.strictEqual(lateErrorSibling.output, undefined); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-args")!), "Second args"); + assert.strictEqual( + sentMessageFromToolItem(tool("send-bare-fail-sibling")!), + "Shared ready", + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-unfinished")!), undefined); + assert.strictEqual( + sentMessageFromToolItem(toolIn(turn2Events, "turn2-leaked-check")!), + undefined, + ); + assert.strictEqual( + previewRecordingIdFromToolItem(tool("recording-stop")!), + `${threadId}-rec-1`, + ); + }).pipe(Effect.provide(layerSession)), + ); }); /** diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 91a00fd60742f..33b2ecd4638c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -43,7 +43,7 @@ import { TestClock } from "effect/testing"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { htmlRenderFromToolItem, sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { @@ -1540,16 +1540,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.interrupt", { interrupted: true }), event("session.execution.interrupted", { sessionID: SESSION }), ]); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const watch = yield* watchBackgroundTurn(runtime); yield* runtime.startTurn(withLineage(thread)); yield* watch.attached; + // The child's nested T3 MCP results live under the root thread and outlive its turn. + const childResult = { message: "Child note" }; + yield* mcpSessions.recordToolResult(threadId, "send_to_user", childResult, { + sentMessage: childResult.message, + }); yield* runtime.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId, }); assert.equal((yield* watch.terminal)?.status, "interrupted"); assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - }), + assert.deepEqual(yield* mcpSessions.takeToolResult(threadId, "send_to_user", childResult), { + sentMessage: childResult.message, + }); + }).pipe(Effect.scoped), ); it.effect("stops background subagents on a user Stop", () => @@ -5321,6 +5331,188 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("shows send_to_user messages a Code Mode script sends without returning them", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const messages = ["First mid-turn note", "Second mid-turn note"]; + yield* Effect.forEach(messages, (message) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ), + ); + const tool = { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-execute-send", + }; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "execute" }), + event("session.tool.called", { ...tool, input: { code: "`; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 0f3f8519bddc7..e70be7cb9f1fc 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -755,7 +755,7 @@ describe("AssetAccess", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" })); - yield* fs.writeFileString(path.join(root, "payload.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4"); const link = path.join(root, "report.pdf"); const issue = issueAssetUrl({ @@ -772,7 +772,7 @@ describe("AssetAccess", () => { return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); }; - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); yield* fs.remove(link); @@ -783,7 +783,7 @@ describe("AssetAccess", () => { }); yield* fs.remove(link); - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect(yield* resolveIssued(issued.relativeUrl)).toBeNull(); }).pipe(Effect.provide(layerTest)), ); @@ -1807,6 +1807,51 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)("refuses a favicon link whose target is not an image", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-" }), + ); + const pictures = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-pictures-" }), + ); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "real.svg"), ""); + const resolveIssued = (relativeUrl: string) => { + const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); + }; + for (const link of [path.join(root, "favicon.svg"), path.join(pictures, "custom.svg")]) { + const issue = issueAssetUrl({ + resource: { _tag: "project-favicon", cwd: root }, + ...(link.startsWith(pictures) ? { projectFaviconPath: link } : {}), + }); + + yield* fs.symlink(path.join(root, "page.xhtml"), link); + expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "real.svg"), link); + const issued = yield* issue; + expect(yield* resolveIssued(issued.relativeUrl)).toEqual({ + kind: "file", + path: path.join(root, "real.svg"), + }); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); + // An outside icon's URL names its target, so repointing the link cannot change it. + expect(yield* resolveIssued(issued.relativeUrl)).toEqual( + link.startsWith(pictures) ? { kind: "file", path: path.join(root, "real.svg") } : null, + ); + yield* fs.remove(link); + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("ignores a client favicon path hint", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 2b8f1029ae3a3..d91975114e6eb 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -287,6 +287,8 @@ const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(functio const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* ( filePath: string, ) { + // Checked again here: a link can be repointed after its URL was issued. + if (!isProjectFaviconPath(filePath)) return null; if (!filePath.toLowerCase().endsWith(".icns")) { return { kind: "file", path: filePath } satisfies ResolvedAsset; } @@ -824,6 +826,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + // A favicon link must resolve to an image file. + if (canonicalFaviconPath && !isProjectFaviconPath(canonicalFaviconPath)) { + return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); + } claims = isExternalOverride && canonicalFaviconPath ? { diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index d7fee1a2271df..f78c4acf28d3d 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -44,7 +44,14 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { + headers: { + "set-cookie": "upstream=1", + "clear-site-data": '"*"', + "content-type": "text/html", + "content-security-policy": "script-src *", + }, + }), ); }), ); @@ -122,6 +129,11 @@ describe("device hub proxy", () => { ); expect(response.status).toBe(200); expect(await response.text()).toBe("frame"); + expect(response.headers.get("set-cookie")).toBeNull(); + expect(response.headers.get("clear-site-data")).toBeNull(); + // Opened as a page, a hub response gets an opaque origin and no script. + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect(requests).toEqual(["http://hub.test/api/devices"]); expect(finalized()).toBe(1); }); diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 9778cf084b017..b7194d1feeeb7 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -164,11 +164,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. + // Clear-Site-Data likewise applies to the origin that serves it. if ( name === "content-encoding" || name === "transfer-encoding" || name === "connection" || - name === "set-cookie" + name === "set-cookie" || + name === "clear-site-data" ) { continue; } @@ -176,6 +178,9 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( } // Long-lived MJPEG and AVCC responses must not be buffered by compression. headers["cache-control"] = "no-store, no-transform"; + // Hub responses are data and streams; none renders as a page on this origin. + headers["x-content-type-options"] = "nosniff"; + headers["content-security-policy"] = "default-src 'none'; sandbox"; const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 6e011aef39d26..2f2f6b8f85534 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -20,6 +20,7 @@ import { openMediaFile } from "./assets/MediaFile.ts"; import { injectMcpAppCsp, injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES, } from "@t3tools/shared/mcpApp"; @@ -54,7 +55,9 @@ describe("MCP app asset responses", () => { method, ), ); - const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)); + const expected = injectMcpAppDocumentBootstrap( + injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)), + ); expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( String(new TextEncoder().encode(expected).byteLength), @@ -842,7 +845,7 @@ describe("video asset byte ranges", () => { }); describe("assetResponseHeaders", () => { - it("sandboxes SVG assets", () => { + it("sandboxes SVG and other XML assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", @@ -850,6 +853,15 @@ describe("assetResponseHeaders", () => { expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty( "Content-Security-Policy", ); + for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) { + expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + ); + } + expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty( + "Content-Security-Policy", + ); }); it("serves inline attachment documents with their declared mime type", () => { expect( diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index acec877a45c55..8a31a99287e38 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -5,7 +5,11 @@ import { EnvironmentHttpApi, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; -import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; +import { + injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, + injectMcpAppThemeBootstrap, +} from "@t3tools/shared/mcpApp"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; @@ -77,6 +81,13 @@ const isSafeInlineMediaMimeType = (mimeType: string): boolean => const isSafeInlineDocumentMimeType = (mimeType: string): boolean => mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; +// XML types render as documents, so they get the same policy as SVG. +const isScriptableXmlPath = (filePath: string): boolean => + Option.match(Mime.getType(filePath), { + onNone: () => false, + onSome: (mimeType) => /(?:\/xml(?:$|-)|\+xml$)/.test(mimeType), + }); + export function downloadContentDisposition(fileName?: string): string { if (fileName === undefined) { return "attachment"; @@ -134,7 +145,7 @@ export function assetResponseHeaders( "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY, } : {}), - ...(!options?.download && lowerPath.endsWith(".svg") + ...(!options?.download && isScriptableXmlPath(lowerPath) ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; @@ -189,6 +200,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( new TextDecoder().decode(bytes), injectMcpAppThemeBootstrap, injectMcpAppCookieBootstrap, + // Applied last so it is the document's first script. + injectMcpAppDocumentBootstrap, (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); diff --git a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx index ed6c4b9261393..2ea2330f50af7 100644 --- a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx +++ b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx @@ -2,6 +2,8 @@ import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; +import { injectMcpAppDocumentBootstrap } from "@t3tools/shared/mcpApp"; + import "~/index.css"; import { act, fakeTimers, render } from "../../../test/render"; @@ -22,10 +24,29 @@ addEventListener("message", (event) => { parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized" }, "*"); `; +const sizeChanged = (height: number) => + `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`; +// What the app's frame shows after the app follows a link: another page in the same window. +// Its nested frame keeps `load`, which stops the app, from firing before its message arrives. +const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(``)}`; +// Served as the server serves an app: the document bootstrap is its first script. +const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(``); + +const asset = vi.hoisted(() => ({ html: "" })); +const setup = (html: string) => { + asset.html = html; +}; + vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: `data:text/html,${encodeURIComponent(APP_HTML)}`, + url: `data:text/html,${encodeURIComponent(asset.html)}`, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -44,6 +65,7 @@ const nextInitializedFrom = () => describe("McpAppFrame", () => { it("keeps a reopened app when the old document's second teardown finishes late", async () => { + setup(APP_HTML); const firstInitialized = nextInitializedFrom(); await using screen = await render( { expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull(); await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument(); }); + + it("ignores a page the app's frame navigated to", async () => { + setup(NAVIGATING_APP_HTML); + const element = () => ( + + ); + await using screen = await render(element()); + const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement; + const row = frame.parentElement!.parentElement!; + // The app resizes only after the host's answer reached it, so the bridge works both ways. + await expect.element(row).toHaveStyle({ height: "321px" }); + + // A tool update hands the row an equal app in a new object, which re-attaches the host. + await screen.rerender(element()); + frame.contentWindow!.postMessage("leave", "*"); + await expect + .element(screen.getByText("The Demo app left its page and was stopped")) + .toBeInTheDocument(); + expect(row.style.height).toBe("321px"); + }); }); diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index c0893c2d6f7c3..3d90a688f717c 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -38,6 +38,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { attachMcpAppDocumentLink } from "./mcpAppDocumentLink"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { @@ -269,16 +270,15 @@ export function McpAppFrame(props: { } return approved; }; - const target = () => frameRef.current?.contentWindow ?? null; const scope = () => { const { environmentId, threadId, itemId } = readLive().props; return { environmentId, input: { threadId, itemId } }; }; + const documentLink = attachMcpAppDocumentLink(frame, (data) => host.receive(data)); const host = makeMcpAppHost({ app, hostVersion: APP_VERSION, - // Opaque origins require "*"; the window reference scopes delivery to this frame. - post: (message) => target()?.postMessage(message, "*"), + post: documentLink.post, hostContext, callTool: async ({ name, arguments: args }) => { const { environmentId, input } = scope(); @@ -401,12 +401,9 @@ export function McpAppFrame(props: { }, }); hostRef.current = host; - const receive = (event: MessageEvent) => { - if (event.source !== null && event.source === target()) host.receive(event.data); - }; - window.addEventListener("message", receive); + window.addEventListener("message", documentLink.receive); return () => { - window.removeEventListener("message", receive); + window.removeEventListener("message", documentLink.receive); void host.teardown(); hostRef.current = null; frameRef.current = null; diff --git a/apps/web/src/components/chat/mcpAppDocumentLink.ts b/apps/web/src/components/chat/mcpAppDocumentLink.ts new file mode 100644 index 0000000000000..6982dd3e12a80 --- /dev/null +++ b/apps/web/src/components/chat/mcpAppDocumentLink.ts @@ -0,0 +1,67 @@ +import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp"; + +const MAX_UNCONFIRMED_MESSAGES = 256; + +interface DocumentLink { + link: MessagePort | "window" | null; + nextProbe: number; + deliver: (data: unknown) => void; + readonly unconfirmed: Map; +} + +// Kept per frame, not per host: a host that re-attaches to the same frame must not take the +// frame's next message for a first one. +const documentLinks = new WeakMap(); + +/** + * Ties the bridge to the frame's first document. A frame's window outlives its document, so the + * bridge follows the port that document's bootstrap sends first, not the window. Servers without + * the bootstrap keep the plain window bridge. + */ +export function attachMcpAppDocumentLink( + frame: HTMLIFrameElement, + deliver: (data: unknown) => void, +) { + let state = documentLinks.get(frame); + if (state === undefined) { + state = { link: null, nextProbe: 0, deliver, unconfirmed: new Map() }; + documentLinks.set(frame, state); + } + const current = state; + current.deliver = deliver; + return { + receive: (event: MessageEvent) => { + if (event.source === null || event.source !== frame.contentWindow) return; + if (current.link === null) { + const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null; + if (port !== null) { + current.link = port; + port.onmessage = (reply: MessageEvent) => { + const probe: unknown = reply.data?.alive; + if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return; + const data = current.unconfirmed.get(probe); + current.unconfirmed.delete(probe); + current.deliver(data); + }; + return; + } + current.link = "window"; + } + if (current.link === "window") { + current.deliver(event.data); + return; + } + // Only the first document can answer, so a reply proves it sent this message. + if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return; + current.unconfirmed.set(current.nextProbe, event.data); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin. + current.link.postMessage({ alive: current.nextProbe }); + current.nextProbe += 1; + }, + post: (message: unknown) => { + // Opaque origins require "*"; the window reference scopes delivery to this frame. + if (current.link === "window") frame.contentWindow?.postMessage(message, "*"); + else current.link?.postMessage({ message, origin: window.location.origin }); + }, + }; +} diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 63a2f119056c1..c0f057a0d508a 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -1,9 +1,5 @@ /* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */ -import { - decodeFilePreviewText, - filePreviewKind, - hostPreviewMimeTypeFromExtension, -} from "@t3tools/shared/filePreview"; +import { decodeFilePreviewText, filePreviewKind } from "@t3tools/shared/filePreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { ChevronLeftIcon, ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react"; import { msg, T, useGT, useMessages } from "gt-react"; @@ -29,6 +25,7 @@ import { type BinaryWorkerRequest, type BinaryWorkerResult, } from "./binaryPreviewProtocol"; +import { archiveImageUrl } from "./archiveImageUrl"; import { PreviewImage } from "./PreviewImage"; import { readBinaryPreview } from "./readBinaryPreview"; import { previewErrorText, previewFailureText } from "./previewFailureMessages"; @@ -69,15 +66,10 @@ function ArchiveFile(props: { readonly path: string; readonly bytes: Uint8Array< // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Create an object URL for the extracted image and revoke it when the entry changes or unmounts. useEffect(() => { if (kind !== "image") return; - const extension = props.path.slice(props.path.lastIndexOf(".")); - const objectUrl = URL.createObjectURL( - new Blob([props.bytes], { - type: hostPreviewMimeTypeFromExtension(extension) ?? "application/octet-stream", - }), - ); + const image = archiveImageUrl(props.path, props.bytes); // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL only after registering its cleanup. - setUrl(objectUrl); - return () => URL.revokeObjectURL(objectUrl); + setUrl(image.url); + return image.revoke; }, [props.bytes, props.path, kind]); if (kind === "image") return url ? : ; diff --git a/apps/web/src/components/files/archiveImageUrl.test.ts b/apps/web/src/components/files/archiveImageUrl.test.ts new file mode 100644 index 0000000000000..90eb11f347831 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.test.ts @@ -0,0 +1,15 @@ +import { expect, it } from "vite-plus/test"; + +import { archiveImageUrl } from "./archiveImageUrl"; + +it("shows an archived SVG from a data URL", () => { + const svg = new TextEncoder().encode(''); + for (const path of ["art/logo.svg", "LOGO.SVG"]) { + expect(archiveImageUrl(path, svg).url).toBe( + `data:image/svg+xml;base64,${btoa(String.fromCharCode(...svg))}`, + ); + } + const png = archiveImageUrl("art/logo.png", new Uint8Array([137, 80, 78, 71])); + expect(png.url).toMatch(/^blob:/); + png.revoke(); +}); diff --git a/apps/web/src/components/files/archiveImageUrl.ts b/apps/web/src/components/files/archiveImageUrl.ts new file mode 100644 index 0000000000000..bdba586d48f11 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.ts @@ -0,0 +1,20 @@ +import { hostPreviewMimeTypeFromExtension } from "@t3tools/shared/filePreview"; +import * as Base64 from "effect/encoding/Base64"; + +/** + * A URL an `` can show for an image taken out of an archive. SVG uses a data: URL, which + * has an opaque origin wherever it is opened; other types use a blob: URL. + */ +export function archiveImageUrl( + path: string, + bytes: Uint8Array, +): { readonly url: string; readonly revoke: () => void } { + const mimeType = + hostPreviewMimeTypeFromExtension(path.slice(path.lastIndexOf("."))) ?? + "application/octet-stream"; + if (mimeType === "image/svg+xml") { + return { url: `data:${mimeType};base64,${Base64.encode(bytes)}`, revoke: () => undefined }; + } + const url = URL.createObjectURL(new Blob([bytes], { type: mimeType })); + return { url, revoke: () => URL.revokeObjectURL(url) }; +} diff --git a/packages/shared/src/mcpApp.ts b/packages/shared/src/mcpApp.ts index 7c3afd221365d..4f25f4ba83317 100644 --- a/packages/shared/src/mcpApp.ts +++ b/packages/shared/src/mcpApp.ts @@ -251,6 +251,23 @@ export function injectMcpAppCookieBootstrap(html: string): string { return `${prefix}${bootstrap}${html.slice(prefix.length)}`; } +export const MCP_APP_DOCUMENT_MESSAGE = "t3-mcp-app-document"; + +/** + * Binds the host bridge to this document rather than to the frame's window, which outlives it. + * The document's first script hands the host a private port: the host answers only over it, and + * acts on a message only once this document confirms it is alive. + */ +export function injectMcpAppDocumentBootstrap(html: string): string { + const bootstrap = ``; + // Preserve captured CSP ahead of executable code, including this bootstrap. + const prefix = + /^(?:\uFEFF?\s*]*>\s*)?(?:)?/i.exec( + html, + )![0]; + return `${prefix}${bootstrap}${html.slice(prefix.length)}`; +} + export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string { const features: Array = []; if (permissions?.camera) features.push("camera"); From ae3352e0512bbd2aa609f7176e1e547f670265f4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 17:40:58 -0600 Subject: [PATCH 046/190] fix(server): checkpoints work when a Git path ends in a space (#41725) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriver.test.ts | 45 ++++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 8 ++--- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 78a436a1424e4..d2eed8bad23a7 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -2098,6 +2098,51 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "checkpoint capture keeps whitespace at the end of Git paths", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-edge-space-capture-", + }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const git = (cwd: string, args: ReadonlyArray) => + driver.execute({ + operation: "test", + cwd, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + }); + const library = path.join(parent, "library"); + yield* fileSystem.makeDirectory(library); + yield* git(library, ["init"]); + yield* git(library, ["commit", "--allow-empty", "-m", "initial"]); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/edge-space"); + // The newline name takes the per-path fallback; the other takes the one-spawn answer. + for (const name of ["repo ", "multi\nline "]) { + const cwd = path.join(parent, name); + yield* fileSystem.makeDirectory(cwd); + yield* git(cwd, ["init", `--separate-git-dir=${path.join(parent, `${name.trim()} git `)}`]); + yield* git(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", library, "lib"]); + yield* git(cwd, ["commit", "-m", "initial"]); + yield* fileSystem.writeFileString(path.join(cwd, "dirty.txt"), "pending\n"); + yield* fileSystem.writeFileString(path.join(cwd, "lib", "dirty.txt"), "nested\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.strictEqual( + (yield* git(cwd, ["show", `${checkpointRef}:dirty.txt`])).stdout, + "pending\n", + ); + assert.strictEqual( + (yield* git(path.join(cwd, "lib"), ["show", `${checkpointRef}:dirty.txt`])).stdout, + "nested\n", + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("restores empty checkpoints without changing paths outside the workspace", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 56b4b44d0156e..bba371104af14 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -992,7 +992,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd, args: ["rev-parse", "--git-common-dir"], }); - const gitCommonDir = result.stdout.trim(); + const gitCommonDir = result.stdout.replace(/\n$/, ""); if (path.isAbsolute(gitCommonDir)) return gitCommonDir; const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return path.resolve(physicalCwd, gitCommonDir); @@ -1025,9 +1025,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const [gitCommonDir = "", indexPath = "", topLevel = "", prefix = "", head = ""] = lines; if (headChecked && lines.length === (headExists ? 6 : 5) && lines.at(-1) === "") { return { - gitCommonDir: gitCommonDir.trim(), - indexPath: indexPath.trim(), - topLevel: topLevel.trim(), + gitCommonDir, + indexPath, + topLevel, prefix, headExists, head: headExists ? head : undefined, From b654fc27baac7bb831c3d21820c263e8667687a7 Mon Sep 17 00:00:00 2001 From: daTuzzo <123642701+daTuzzo@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:41:11 +0200 Subject: [PATCH 047/190] fix(server): automatic port selection checks the address the server binds (#41730) Co-authored-by: Julius Marminge --- apps/server/src/cli/automaticPort.test.ts | 6 +++-- apps/server/src/cli/automaticPort.ts | 10 ++++--- apps/server/src/cli/config.test.ts | 17 ++++++++---- apps/server/src/cli/config.ts | 33 ++++++++++++----------- packages/shared/src/Net.test.ts | 23 ++++++++++++++++ packages/shared/src/Net.ts | 23 +++++++++++++--- packages/shared/src/hostClassification.ts | 4 +++ 7 files changed, 86 insertions(+), 30 deletions(-) diff --git a/apps/server/src/cli/automaticPort.test.ts b/apps/server/src/cli/automaticPort.test.ts index 1f7805569744f..b39c94720cbc8 100644 --- a/apps/server/src/cli/automaticPort.test.ts +++ b/apps/server/src/cli/automaticPort.test.ts @@ -34,6 +34,7 @@ interface Scenario { readonly tcpv6ExitCode?: number; readonly wslpathMissing?: boolean; readonly reservedPorts?: ReadonlyArray; + readonly host?: string; } const select = (scenario: Scenario) => { @@ -92,7 +93,7 @@ const select = (scenario: Scenario) => { ); return Effect.gen(function* () { const selectAutomaticPort = yield* AutomaticPort.make; - const port = yield* selectAutomaticPort(3773); + const port = yield* selectAutomaticPort(3773, scenario.host); return { port, commands }; }).pipe(Effect.provide(layer)); }; @@ -149,12 +150,13 @@ describe("automatic port selection", () => { }), ); - it.effect("never queries Windows outside WSL", () => + it.effect("never queries Windows outside WSL or for a specific bind address", () => Effect.gen(function* () { for (const scenario of [ { kernelRelease: "6.8.0-45-generic\n" }, // macOS and Windows have no kernel release file. {}, + { kernelRelease: WSL_KERNEL, windowsPorts: [3773], host: "100.64.0.7" }, ] satisfies ReadonlyArray) { const result = yield* select(scenario); expect(result.port).toBe(3773); diff --git a/apps/server/src/cli/automaticPort.ts b/apps/server/src/cli/automaticPort.ts index 354de65d2519b..70e8bad6c8b05 100644 --- a/apps/server/src/cli/automaticPort.ts +++ b/apps/server/src/cli/automaticPort.ts @@ -1,3 +1,4 @@ +import { listensOnLoopback } from "@t3tools/shared/hostClassification"; import * as NetService from "@t3tools/shared/Net"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -44,14 +45,17 @@ export const make = Effect.gen(function* () { return new Set(listeners.map((listener) => listener.port)); }).pipe(Effect.orElseSucceed(() => null)); - return Effect.fn("automaticPort.select")(function* (preferred: number) { - if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred); + return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) { + // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address. + if (!listensOnLoopback(host) || !(yield* isWsl)) { + return yield* net.findAvailablePort(preferred, host); + } const windows = yield* readWindowsHostListeners; if (windows === null) { yield* Effect.logWarning( "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.", ); - return yield* net.findAvailablePort(preferred); + return yield* net.findAvailablePort(preferred, host); } if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) { return preferred; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 9d1ffb5c1298a..bbd13c1132953 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -872,15 +872,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const baseDir = yield* FileSystem.FileSystem.pipe( Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })), ); - const selected: number[] = []; - const selectAutomaticPort = (preferred: number) => + const selected: Array = []; + const selectAutomaticPort = (preferred: number, host: string | undefined) => Effect.sync(() => { - selected.push(preferred); + selected.push([preferred, host]); return 50_123; }); const resolvePort = (flags: { readonly mode?: Option.Option<"web" | "desktop">; readonly port: Option.Option; + readonly host?: Option.Option; }) => resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), { selectAutomaticPort, @@ -895,12 +896,18 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); expect(yield* resolvePort({ port: Option.none() })).toBe(50_123); - expect(selected).toEqual([3773]); + expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe( + 50_123, + ); + expect(selected).toEqual([ + [3773, undefined], + [3773, "100.64.0.7"], + ]); expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788); expect( yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }), ).toBe(3773); - expect(selected).toEqual([3773]); + expect(selected).toHaveLength(2); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a62682772bcce..87ff2588c5e34 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -271,6 +271,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct readonly rejectRunningServer?: boolean; readonly selectAutomaticPort?: ( preferred: number, + host: string | undefined, ) => Effect.Effect; }, ) { @@ -310,22 +311,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct () => "web", ); - const port = yield* Option.match( - resolveOptionPrecedence( - normalizedFlags.port, - Option.fromUndefinedOr(env.port), - Option.fromUndefinedOr(bootstrap?.port), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(ServerConfig.DEFAULT_PORT); - } - return selectAutomaticPort(ServerConfig.DEFAULT_PORT); - }, - }, - ); const devUrl = Option.getOrElse( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, @@ -451,6 +436,22 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const host = Option.getOrElse(explicitHost, () => privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined, ); + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + Option.fromUndefinedOr(bootstrap?.port), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(ServerConfig.DEFAULT_PORT); + } + return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host); + }, + }, + ); const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); const otel = yield* OtelEnvironment.load; diff --git a/packages/shared/src/Net.test.ts b/packages/shared/src/Net.test.ts index d4b00f5f957da..ca86a5db4a46f 100644 --- a/packages/shared/src/Net.test.ts +++ b/packages/shared/src/Net.test.ts @@ -1,4 +1,5 @@ import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -44,6 +45,10 @@ const openServer = (host?: string): Effect.Effect entries ?? []) + .find((entry) => entry.family === "IPv4" && !entry.internal)?.address; + it.layer(NetService.layer)("NetService", (it) => { describe("Net helpers", () => { it.effect.each(["EAFNOSUPPORT", "EADDRNOTAVAIL"])( @@ -99,9 +104,27 @@ it.layer(NetService.layer)("NetService", (it) => { const resolved = yield* net.findAvailablePort(preferred); assert.ok(resolved > 0); assert.notEqual(resolved, preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, ownIpv4), preferred); }), closeServer, ), ); + + it.effect.skipIf(ownIpv4 === undefined)( + "findAvailablePort keeps a port that only loopback uses for a specific bind address", + () => + Effect.acquireUseRelease( + openServer("127.0.0.1"), + (server) => + Effect.gen(function* () { + const net = yield* NetService.NetService; + const preferred = getPort(server); + + assert.equal(yield* net.findAvailablePort(preferred, ownIpv4), preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, "0.0.0.0"), preferred); + }), + closeServer, + ), + ); }); }); diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.ts index 40ef669db4e64..5a8f3214f177c 100644 --- a/packages/shared/src/Net.ts +++ b/packages/shared/src/Net.ts @@ -6,6 +6,8 @@ import * as Context from "effect/Context"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import { listensOnLoopback } from "./hostClassification.ts"; + export class NetError extends Schema.TaggedError()("NetError", { message: Schema.String, cause: Schema.optional(Schema.Defect()), @@ -35,7 +37,7 @@ export interface NetServiceShape { readonly reserveLoopbackPort: (host?: string) => Effect.Effect; - readonly findAvailablePort: (preferred: number) => Effect.Effect; + readonly findAvailablePort: (preferred: number, host?: string) => Effect.Effect; } export class NetService extends Context.Service()( @@ -130,6 +132,19 @@ export const make = () => { ); }); + const isPortAvailableForHost = Effect.fn("Net.isPortAvailableForHost")(function* ( + port: number, + host: string | undefined, + ): Effect.fn.Return { + if (host === undefined || listensOnLoopback(host)) { + return yield* isPortAvailableOnLoopback(port); + } + if (yield* hasListenerOnHost(port, host)) { + return false; + } + return yield* canListenOnHost(port, host); + }); + const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect => Effect.callback((resume) => { const probe = NodeNet.createServer(); @@ -167,11 +182,11 @@ export const make = () => { isPortAvailableOnLoopback, hasListenerOnHost, reserveLoopbackPort, - findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred) { - if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) { + findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred, host) { + if (preferred > 0 && (yield* isPortAvailableForHost(preferred, host))) { return preferred; } - return yield* reserveLoopbackPort(); + return yield* reserveLoopbackPort(listensOnLoopback(host) ? undefined : host); }), } satisfies NetServiceShape; }; diff --git a/packages/shared/src/hostClassification.ts b/packages/shared/src/hostClassification.ts index b10b226ec35c7..a9951a869d332 100644 --- a/packages/shared/src/hostClassification.ts +++ b/packages/shared/src/hostClassification.ts @@ -179,5 +179,9 @@ export const isPublicFaviconHost = (host: string): boolean => { export const isWildcardHost = (host: string | undefined): boolean => host === "0.0.0.0" || host === "::" || host === "[::]"; +/** An unset, loopback, or wildcard bind host shares the port that `localhost` clients reach. */ +export const listensOnLoopback = (host: string | undefined): boolean => + host === undefined || host === "" || isWildcardHost(host) || isLocalLoopbackHost(host); + export const formatHostForUrl = (host: string): string => host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; From 8217726c1068751b1951058cf1b185c1091e687a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:42:07 -0800 Subject: [PATCH 048/190] fix(server): cut-off checkpoint captures no longer strand Git LFS temp files (#41697) --- apps/server/src/vcs/GitVcsDriver.test.ts | 181 +++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 68 +++++++++ 2 files changed, 249 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index d2eed8bad23a7..9ef6c1e7a9324 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -369,6 +369,187 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each(["interrupt", "timeout"] as const)( + "checkpoint staging $0 removes the Git LFS temp files its clean filter wrote", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const lfsTmp = path.join(cwd, ".git/lfs/tmp"); + yield* fs.makeDirectory(lfsTmp, { recursive: true }); + const otherOperation = path.join(lfsTmp, "owned-by-another-git-lfs"); + yield* fs.writeFileString(otherOperation, "another git-lfs process is hashing this"); + + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + // Like git-lfs clean: copy the content into /tmp while hashing, and only + // move or remove that copy once hashing finishes. A killed filter strands it. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, Buffer.alloc(1024 * 1024));", + `const s = require('node:net').connect(${address.port}, '127.0.0.1');`, + "s.resume(); process.stdin.resume();", + "s.on('close', () => process.exit(0));", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.promise(() => connected.promise); + const laterOperation = path.join(lfsTmp, "started-during-capture"); + yield* fs.writeFileString(laterOperation, "another git-lfs process started later"); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + + assert.sameMembers(yield* fs.readDirectory(lfsTmp), [ + "owned-by-another-git-lfs", + "started-during-capture", + ]); + assert.strictEqual( + yield* fs.readFileString(otherOperation), + "another git-lfs process is hashing this", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint staging moves Git LFS objects its clean filter wrote into LFS storage", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // Like git-lfs clean: hash through /tmp, then move the copy into objects. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "const content = fs.readFileSync(0);", + "const oid = require('node:crypto').createHash('sha256').update(content).digest('hex');", + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "const dir = storage + '/objects/' + oid.slice(0, 2) + '/' + oid.slice(2, 4);", + "fs.mkdirSync(dir, { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, content);", + "fs.renameSync(storage + '/tmp/' + process.pid, dir + '/' + oid);", + "process.stdout.write('oid sha256:' + oid + '\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + const pointer = yield* git(["show", `${checkpointRef}:weights.npz`]); + const oid = pointer.stdout.trim().slice("oid sha256:".length); + assert.strictEqual( + yield* fs.readFileString( + path.join(cwd, ".git/lfs/objects", oid.slice(0, 2), oid.slice(2, 4), oid), + ), + "large untracked data\n", + ); + assert.isFalse(yield* fs.exists(path.join(cwd, ".git/lfs/tmp"))); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture fails instead of dropping Git LFS objects it cannot list", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // A file where git-lfs keeps its objects makes the store unreadable without being absent. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.readFileSync(0);", + "fs.mkdirSync(storage, { recursive: true });", + "fs.writeFileSync(storage + '/objects', 'not a directory');", + "process.stdout.write('pointer\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const result = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit); + + const error = Exit.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + const ref = yield* driver.execute({ + operation: "checkpoint-test", + cwd, + args: ["rev-parse", "--verify", "--quiet", checkpointRef], + allowNonZeroExit: true, + }); + assert.strictEqual(ref.exitCode, 1); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index bba371104af14..551c863510423 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1259,6 +1259,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // git-lfs's clean filter copies each file into /tmp while hashing it and strands + // that copy when killed. Give it storage that is removed with the capture's private objects. + const privateLfs = path.join(privateObjects, "lfs"); + const publishLfsObjects = Effect.gen(function* () { + const source = path.join(privateLfs, "objects"); + const objects = (yield* fileSystem.readDirectory(source, { recursive: true }).pipe( + // Absent when no file went through the filter; any other failure must stop publication. + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "publish", + cause, + }), + ), + )).filter((entry) => /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/.test(entry)); + if (objects.length === 0) return; + const configured = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + // git-lfs resolves a relative lfs.storage against the common Git directory. + const storage = path.resolve(gitCommonDir, configured.stdout.trim() || "lfs"); + yield* Effect.forEach( + objects, + (entry) => + Effect.gen(function* () { + const from = path.join(source, entry); + const to = path.join(storage, "objects", entry); + if (yield* fileSystem.exists(to)) return; + yield* fileSystem.makeDirectory(path.dirname(to), { recursive: true }); + // Identical oids are interchangeable, so losing a race to another writer is fine. + // lfs.storage may be on another volume, where only a copy can move the object. + const partial = `${to}.${indexId}`; + yield* fileSystem.rename(from, to).pipe( + Effect.catch((cause) => + Effect.flatMap(fileSystem.exists(to), (exists) => + exists + ? Effect.void + : fileSystem.copyFile(from, partial).pipe( + Effect.andThen(fileSystem.rename(partial, to)), + Effect.ensuring( + fileSystem.remove(partial, { force: true }).pipe(Effect.ignore), + ), + Effect.mapError(() => cause), + ), + ), + ), + ); + }), + { concurrency: 16, discard: true }, + ).pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + }); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1272,6 +1337,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + // Any command on the scratch index can run the clean filter, not just add. + ...VcsProcess.gitConfigEnv(hostEnv, "lfs.storage", privateLfs, hostPlatform), }; const cleanupTempIndex = Effect.forEach( @@ -1791,6 +1858,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + yield* publishLfsObjects; // Git writers have exited; bound publication by fanout directory. yield* fileSystem.readDirectory(privateObjects).pipe( Effect.flatMap((directories) => From 5ab8dc4bfcc6568786a46abec867183e6b8442d4 Mon Sep 17 00:00:00 2001 From: Dibas <81339759+dibas-np@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:28:36 +0545 Subject: [PATCH 049/190] fix(mobile): show every image when Markdown puts one per line (#30280) Co-authored-by: Julius Marminge --- apps/mobile/src/lib/markdownDocument.ts | 35 ++++++++++++++++++++++-- apps/mobile/src/lib/markdownHtml.test.ts | 25 +++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index b44b96fca49b8..c11d00bc9aae0 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -498,13 +498,44 @@ function markdownWithWindowsPathDestinations(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference"; +const isSpace = (node: MarkdownNode) => + node.type === "break" || (node.type === "text" && node.value.trim() === ""); + +// Native Markdown sizes an image as a block only when it is its paragraph's only child. +function markdownWithImageParagraphs(markdown: string): string { + // Skips the extra parse unless a line ending sits between two images. + if (!/[\])][ \t]*\\?(?:\r\n?|\n)[ \t]*!\[/.test(markdown)) return markdown; + const edits: MarkdownEdit[] = []; + for (const block of parser.parse(markdown).children) { + if ( + block.type !== "paragraph" || + !block.children.every((child) => isImage(child) || isSpace(child)) + ) + continue; + const images = block.children.filter(isImage); + for (const [index, image] of images.slice(1).entries()) { + const start = images[index]!.position?.end.offset; + const end = image.position?.start.offset; + if (start === undefined || end === undefined) continue; + const ending = /\r\n?|\n/.exec(markdown.slice(start, end)); + if (ending) edits.push({ start, end, content: ending[0].repeat(2) }); + } + } + return applyMarkdownEdits(markdown, edits); +} + // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. -export function markdownForNativeParsing(markdown: string): string { +function normalizedMarkdown(markdown: string): string { return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); } +export function markdownForNativeParsing(markdown: string): string { + return markdownWithImageParagraphs(normalizedMarkdown(markdown)); +} + export function parseMarkdownDocument(markdown: string): Root { - return parser.parse(markdownForNativeParsing(markdown)); + return parser.parse(normalizedMarkdown(markdown)); } export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 64c5d02df3532..6cce7f84b475c 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + markdownForNativeParsing, markdownForNativeRendering, markdownHtmlContent, markdownWithHtml, @@ -303,6 +304,30 @@ describe("file embeds in native thread and file Markdown", () => { } }); + it("gives each image on its own line its own native paragraph", async () => { + const images = + "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]"; + const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`; + const paragraphs = ( + await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX)) + ).children?.map((block) => block.children?.map((child) => child.type).join(" ")); + expect(paragraphs).toEqual([ + "Text", + "Image", + "Image", + "Image", + "Image Text Image", + "Image", + "Text", + ]); + expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe( + "![a](./a.png)\r\n\r\n![b](./b.png)", + ); + expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe( + "![a](./a.png)\r\r![b](./b.png)", + ); + }); + it("retains standalone audio players and image/video embeds in threads", () => { const source = "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)"; From 0d6fe2141abe62de48d5b836d4ff8b26f37308b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:44:06 -0800 Subject: [PATCH 050/190] fix(server): mode limits follow the turn a message joins (#41746) Co-authored-by: Claude Fable 5.2 --- .../src/mcp/OrchestratorMcpService.test.ts | 56 ++++- apps/server/src/mcp/OrchestratorMcpService.ts | 56 +++-- .../src/orchestration-v2/Orchestrator.ts | 94 ++++++-- .../ProviderTurnStartService.test.ts | 2 + .../ProviderTurnStartService.ts | 4 + .../SteeringCompletion.integration.test.ts | 221 ++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 10 +- docs/user/cursor.md | 4 +- packages/contracts/src/orchestrationV2.ts | 4 + .../src/server/adapter.test.ts | 20 +- .../provider-cursor/src/server/adapter.ts | 34 ++- .../src/server/workspaceMcpServers.ts | 4 +- 12 files changed, 456 insertions(+), 53 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 551a84109cfa2..c99f9b0a6e1ad 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3950,6 +3950,8 @@ describe("OrchestratorMcpService provider resolution", () => { boundThread: OrchestrationV2ThreadShell | null, upserted: Ref.Ref, saved: ScheduledTask = tasks[0]!, + /** Stores each keyed create under the id its key derives, as the real service does. */ + created?: Ref.Ref>, ) => OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -3984,9 +3986,24 @@ describe("OrchestratorMcpService provider resolution", () => { Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ - list: () => Effect.succeed({ tasks }), - upsert: () => - Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), + list: () => + created === undefined + ? Effect.succeed({ tasks }) + : Ref.get(created).pipe(Effect.map((stored) => ({ tasks: stored }))), + upsert: (input) => + Ref.update(upserted, (count) => count + 1).pipe( + Effect.andThen( + created === undefined || input.commandId === undefined + ? Effect.void + : Ref.set(created, [ + { + ...saved, + id: ScheduledTaskService.scheduledTaskIdForCommand(input.commandId), + }, + ]), + ), + Effect.as({ task: saved }), + ), }), ), ), @@ -4084,6 +4101,39 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "refuses to replay a creation over a task whose thread now runs above the caller", + () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const created = yield* Ref.make>([]); + const bound = task({ threadId: boundThreadId }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + [bound], + liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), + upserted, + bound, + created, + ), + ), + ); + const create = (prompt: string) => + mcp.scheduleTask(supervisedClient, { + projectId, + prompt, + schedule: { type: "webhook" }, + freshSession: true, + clientRequestId: "nightly", + }); + yield* create("Check the build"); + const error = yield* create("Something else").pipe(Effect.flip); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.equal(yield* Ref.get(upserted), 1); + }), + ); + it.effect("reports a saved task even when its bound thread cannot be read", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8b58504247ba9..825094d4027e0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2369,6 +2369,21 @@ const make = Effect.gen(function* () { }, ); + const requireScheduledTaskWithinLimits = Effect.fn( + "OrchestratorMcpService.requireScheduledTaskWithinLimits", + )(function* ( + task: ScheduledTask, + limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, + ) { + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + }); + /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above @@ -2392,10 +2407,7 @@ const make = Effect.gen(function* () { if (task === undefined) { return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } + yield* requireScheduledTaskWithinLimits(task, limits); return task; }); @@ -2423,6 +2435,16 @@ const make = Effect.gen(function* () { .slice(0, 80) .replace(/[\uD800-\uDBFF]$/, ""); const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task"); + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + const commandId = + input.clientRequestId === undefined + ? undefined + : stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", + }); const upsertInput: ScheduledTaskUpsertInput = { title, prompt: input.prompt, @@ -2441,18 +2463,22 @@ const make = Effect.gen(function* () { interactionMode: limits.interactionMode, createdBy: "agent", creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), - }), + ...(commandId === undefined ? {} : { commandId }), }; + // A replayed key rewrites the task it created, which its user may since have raised or + // rebound: that is an edit of the task as it now stands. + if (commandId !== undefined) { + const replayedId = ScheduledTaskService.scheduledTaskIdForCommand(commandId); + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const replayed = tasks.find((candidate) => candidate.id === replayedId); + if (replayed !== undefined) yield* requireScheduledTaskWithinLimits(replayed, limits); + } const { task } = yield* scheduledTasks .upsert(upsertInput) .pipe( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8547084085e6b..7dc93dc5c196e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6018,6 +6018,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + // A turn keeps the modes it started with, so a thread lowered since can hold a broader one. + // A turn that recorded none is taken as unrestricted. + const turnStartedModes = ( + attempts: ReadonlyArray, + run: OrchestrationV2Run | undefined, + ) => + attempts.find((attempt) => attempt.id === run?.activeAttemptId)?.startedModes ?? { + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + }; + + // A parked steer is delivered later by the server, without the caller's limit, into a turn + // whose modes are not recorded yet. Only a caller allowed any turn may park or rewrite one. + const limitForbidsParkedSteer = Effect.gen(function* () { + const limit = narrowToCeiling(yield* DispatchModeLimit, runtimeModeCeiling); + return ( + limit !== undefined && + exceededDispatchModeLimit(limit, { + runtimeMode: "full-access", + interactionMode: "default", + }) !== undefined + ); + }); + const refuseAboveDispatchModeLimit = Effect.fn("orchestrationV2.dispatch.refuseAboveModeLimit")( function* ( command: OrchestrationV2ServerCommand, @@ -6694,6 +6718,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if (steeringPolicy === "active_steering") { + yield* refuseAboveDispatchModeLimit( + input.command, + input.command.threadId, + turnStartedModes(input.projection.attempts, targetRun), + ); const instanceChanged = input.projection.thread.providerInstanceId !== input.modelSelection.instanceId; // Only a user's steer carries the picker's selection; the adapter applies it to the live turn. @@ -7960,21 +7989,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { - const adapter = yield* providerAdapters - .get(target.providerInstanceId) - .pipe(mapDispatchError(command)); - const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); - yield* commandPolicy - .decideSteeringExecution({ - commandId: command.commandId, - threadId: command.threadId, - providerInstanceId: target.providerInstanceId, - capabilities, - }) - .pipe(mapDispatchError(command)); - yield* ensureSteeringMessage(command, command); - steerWhenReadyRunId = target.id; - dispatchMode = { type: "queue_after_active" }; + // Such a caller's message waits for its own turn instead. + if (yield* limitForbidsParkedSteer) { + dispatchMode = { type: "queue_after_active" }; + } else { + const adapter = yield* providerAdapters + .get(target.providerInstanceId) + .pipe(mapDispatchError(command)); + const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); + yield* commandPolicy + .decideSteeringExecution({ + commandId: command.commandId, + threadId: command.threadId, + providerInstanceId: target.providerInstanceId, + capabilities, + }) + .pipe(mapDispatchError(command)); + yield* ensureSteeringMessage(command, command); + steerWhenReadyRunId = target.id; + dispatchMode = { type: "queue_after_active" }; + } } } if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { @@ -11577,6 +11611,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runtimeRequest.responseCapability.type === "live" ? runtimeRequest.responseCapability.providerSessionId : null; + if (providerSessionId !== null && (yield* DispatchModeLimit) !== undefined) { + // The answer goes into the turn that asked, which keeps the modes it started with. + const live = yield* projectionStore + .getThreadRecords(command.threadId, ["runs", "attempts"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + yield* refuseAboveDispatchModeLimit( + command, + command.threadId, + turnStartedModes( + live.attempts, + live.runs.find((run) => run.id === context.node?.runId), + ), + ); + } const providerSession = context.session; if (providerSessionId !== null && providerSession === undefined) { return yield* new OrchestratorDispatchError({ @@ -12171,6 +12223,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { + if (yield* limitForbidsParkedSteer) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The current turn is not running yet. Try again once it is.", + }); + } yield* ensureSteeringMessage(command, queuedMessage); const adapter = yield* providerAdapters .get(target.providerInstanceId) @@ -12576,10 +12635,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A command cannot steer, so an edit into one keeps it queued where it is. if ( queuedRun.steerWhenReadyRunId !== undefined && - isSlashCommand({ + (isSlashCommand({ text: command.text, attachments: command.attachments ?? queuedMessage.attachments, - }) + }) || + (yield* limitForbidsParkedSteer)) ) { const { steerWhenReadyRunId: _, ...queued } = queuedRun; yield* emitEvent({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index ef9bd2bb32712..bcb75e097a5bb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -582,6 +582,8 @@ function makeLocalCommandHarness(input: { id: threadId, activeProviderThreadId: providerThreadId, projectId: ProjectId.make("project-native-account-command"), + runtimeMode: "full-access", + interactionMode: "default", branch: input.worktreePath === undefined ? null : "feature/restore", worktreePath: input.worktreePath ?? null, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 1cb77e387f950..e66506fa31f8c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1959,6 +1959,10 @@ export const layer: Layer.Layer< : { nativeThreadId: runningProviderThread.nativeThreadRef.nativeId }), status: "running", startedAt: now, + startedModes: { + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + }, }; const runningRootNode: OrchestrationV2ExecutionNode = { ...rootNode, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 4a665211ef68b..7798a7e00e267 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -14,6 +14,7 @@ import { ProviderInstanceId, ProviderThreadId, ProviderTurnId, + RuntimeRequestId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ScheduledTaskId, ThreadId, @@ -34,6 +35,7 @@ import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { DispatchModeLimit } from "./DispatchModeLimit.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; @@ -512,6 +514,8 @@ const composerSelection = { options: [...runSelection.options, { id: "fastMode", value: false }], }; +const supervised = { runtimeMode: "approval-required", interactionMode: "default" } as const; + const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* ( name: string, canRestart = false, @@ -1940,6 +1944,223 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it" }), ); +it.effect( + "refuses a limited caller's steer into a turn started before its thread was lowered", + () => + Effect.gen(function* () { + const { steered, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("steer-above-limit"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Codex keeps its session, and its running turn the full-access policy it started with. + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const steer = { + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "follow up", + attachments: [], + dispatchMode: { type: "start_immediately" }, + deliveryIntent: "steer", + createdBy: "agent", + creationSource: "mcp", + } as const; + const refused = yield* orchestrator + .dispatch(steer) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + yield* worker.drain(); + assert.deepEqual(steered, []); + + // The refusal records nothing, and a caller without the limit still reaches the turn. + yield* orchestrator.dispatch(steer); + yield* worker.drain(); + assert.lengthOf(steered, 1); + + // The turn's own record decides: one that started within the limit takes the steer. + const attempt = (yield* orchestrator.getThreadProjection(threadId)).attempts[0]!; + assert.deepEqual(attempt.startedModes, { + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("started-supervised"), + type: "run-attempt.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...attempt, startedModes: supervised }, + }, + ], + }); + yield* orchestrator + .dispatch({ + ...steer, + commandId: CommandId.make("steer-within"), + messageId: MessageId.make("message:steer-within"), + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + yield* worker.drain(); + assert.lengthOf(steered, 2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("queues a limited caller's steer into a turn that is not running yet", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("steer-not-ready"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + const steer = (name: string) => + ({ + type: "message.dispatch", + commandId: CommandId.make(name), + threadId, + messageId: MessageId.make(`message:${name}`), + text: "follow up", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }) as const; + const queuedBy = Effect.fn("queuedBy")(function* (name: string) { + return (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make(`message:${name}`), + )!; + }); + // Every MCP caller carries a limit; one at full access parks its steer like the owner. + yield* orchestrator.dispatch(steer("parked")).pipe( + Effect.provideService(DispatchModeLimit, { + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + const parked = yield* queuedBy("parked"); + assert.equal(parked.steerWhenReadyRunId, started[0]!.runId); + + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + // A parked steer is delivered by the server itself, which carries no caller limit. + yield* orchestrator + .dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit-parked"), + threadId, + runId: parked.id, + text: "rewritten", + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + assert.isUndefined((yield* queuedBy("parked")).steerWhenReadyRunId); + + yield* orchestrator + .dispatch(steer("steer")) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + const queued = yield* queuedBy("steer"); + assert.isUndefined(queued.steerWhenReadyRunId); + + yield* orchestrator + .dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queued.id, + targetRunId: started[0]!.runId, + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + const kept = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === queued.id, + )!; + assert.equal(kept.status, "queued"); + assert.isUndefined(kept.steerWhenReadyRunId); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("refuses a limited caller's answer to a turn started above its limit", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("answer-above"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const now = yield* DateTime.now; + const requestId = RuntimeRequestId.make("request:question"); + const session = (yield* orchestrator.getThreadProjection(threadId)).providerSessions[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("question"), + type: "runtime-request.updated", + threadId, + occurredAt: now, + payload: { + id: requestId, + nodeId: started[0]!.rootNodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status: "pending", + responseCapability: { type: "live", providerSessionId: session.id }, + createdAt: now, + resolvedAt: null, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const respond = { + type: "runtime-request.respond", + commandId: CommandId.make("respond"), + threadId, + requestId, + decision: "accept", + } as const; + const refused = yield* orchestrator + .dispatch(respond) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + + yield* orchestrator.dispatch(respond); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).runtimeRequests[0]?.status, + "resolved", + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #39404 a later agent message steers ahead of one queued behind /compact it.effect("delivers agent messages queued behind /compact before a later one steers", () => Effect.gen(function* () { diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 3db6f783f649a..488852884f69e 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -81,6 +81,10 @@ import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookF import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts"; export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; + +/** The task a create carrying this idempotency key writes, and rewrites when the key is replayed. */ +export const scheduledTaskIdForCommand = (commandId: CommandId) => + ScheduledTaskId.make(`scheduled-task:${commandId}`); const isScheduledTaskError = Schema.is(ScheduledTaskError); const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError); const PROMPT_TOO_LONG = "The filled-in prompt is too long."; @@ -1480,9 +1484,9 @@ export const layer = Layer.effect( : null; const id = input.id ?? - ScheduledTaskId.make( - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, - ); + (input.commandId + ? scheduledTaskIdForCommand(input.commandId) + : ScheduledTaskId.make(`scheduled-task:${uuid}`)); // Look up by the *resolved* id so idempotent creates (commandId replays) // keep their run history, and so real load failures propagate instead // of silently resetting an existing row. diff --git a/docs/user/cursor.md b/docs/user/cursor.md index f10ca24fb596f..f78ccf343d0cb 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -17,7 +17,9 @@ not expose yet. Custom Cursor MCP servers and plugins are not configured in T3 Code. They load from the environment machine's Cursor config when the agent opens: project `.cursor/mcp.json`, user `~/.cursor/mcp.json`, -and installed plugins under `~/.cursor/plugins`. Plugin tools +and installed plugins under `~/.cursor/plugins`. A project's own Cursor config, including its +`.cursor/mcp.json`, loads only in **Full access**; in the other +[permission modes](./permission-modes.md) a checkout cannot start MCP servers. Plugin tools can appear without a login; OAuth MCP servers still need credentials. Run `agent mcp login ` with the cwd set to the T3 project root (tokens land in `~/.cursor/projects//mcp-auth.json`). Cursor desktop Connections auth does not write diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8843d8cacf805..dfde87c009f66 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -897,6 +897,10 @@ export const OrchestrationV2RunAttempt = Schema.Struct({ ]), startedAt: Schema.NullOr(Schema.DateTimeUtc), completedAt: Schema.NullOr(Schema.DateTimeUtc), + /** The thread's modes when this attempt's turn started. A later change reaches only the next turn. */ + startedModes: Schema.optional( + Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }), + ), }); export type OrchestrationV2RunAttempt = typeof OrchestrationV2RunAttempt.Type; diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 4e687ed2b9c9e..90db987cf2c99 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -3275,7 +3275,7 @@ describe("CursorAdapterV2", () => { const workspace = path.join(scratch, "workspace"); const home = path.join(scratch, "home"); const loadServers = () => - cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }).pipe( + cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }, { includeProject: true }).pipe( Effect.provideService(HostProcess.HomeDirectory, home), Effect.provideService(HostProcess.Environment, {}), ); @@ -3398,13 +3398,13 @@ describe("CursorAdapterV2", () => { Effect.provideService(HostProcess.Environment, {}), ); const now = yield* DateTime.now; - const sendTurn = (ordinal: number) => + const sendTurn = (ordinal: number, turnPolicy = runtimePolicy) => runtime .startTurn({ threadId, providerThread, modelSelection, - runtimePolicy, + runtimePolicy: turnPolicy, runId: RunId.make(`cursor-mcp-run-${ordinal}`), runOrdinal: ordinal, providerTurnOrdinal: ordinal, @@ -3479,6 +3479,20 @@ describe("CursorAdapterV2", () => { ); yield* sendTurn(3); assert.deepEqual(sentWith[2], t3Servers); + // A restricted turn starts no command the checkout names; the user's own file still applies. + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), + "[]", + ); + for (const [index, runtimeMode] of ( + ["approval-required", "auto-accept-edits", "auto"] as const + ).entries()) { + yield* sendTurn(4 + index, { ...runtimePolicy, runtimeMode }); + assert.deepEqual(sentWith[3 + index], { + repro: { command: "node", args: [`${home}/shadowed.mjs`], cwd: projectRoot }, + ...t3Servers, + }); + } yield* fileSystem.writeFileString( path.join(workspace, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index c758e46a7b3dc..042adcc9c3e9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -309,6 +309,17 @@ const CURSOR_AGENT_SETTING_SOURCES = [ "plugins", ] as const satisfies ReadonlyArray; +/** Whether the checkout's own Cursor config (settings, hooks, MCP servers) may load: only unrestricted turns. */ +function cursorLoadsProjectConfig( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + platform: NodeJS.Platform, +): boolean { + const policy = cursorRuntimeAgentPolicy(runtimePolicy, platform); + return ( + runtimePolicy.runtimeMode === "full-access" && !policy.autoReview && !policy.sandboxEnabled + ); +} + export function makeCursorAgentOptions(input: { readonly apiKey?: string; readonly modelSelection: ModelSelection; @@ -332,12 +343,9 @@ export function makeCursorAgentOptions(input: { ? {} : { dirs: [...input.runtimePolicy.workspace.extraRoots] }), autoReview: policy.autoReview, - settingSources: - input.runtimePolicy.runtimeMode === "full-access" && - !policy.autoReview && - !policy.sandboxEnabled - ? [...CURSOR_AGENT_SETTING_SOURCES] - : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), + settingSources: cursorLoadsProjectConfig(input.runtimePolicy, input.platform) + ? [...CURSOR_AGENT_SETTING_SOURCES] + : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), sandboxOptions: { enabled: policy.sandboxEnabled, }, @@ -2731,10 +2739,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( } }; - const resolveWorkspaceMcpServers = (cwd: string | null) => - cwd === null + const resolveWorkspaceMcpServers = ( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + ) => { + const { cwd } = runtimePolicy; + return cwd === null ? Effect.succeed({}) - : cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe( + : cursorWorkspaceMcpServers(cwd, adapterOptions.environment, { + includeProject: cursorLoadsProjectConfig(runtimePolicy, platform), + }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -2746,6 +2759,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as({})), ), ); + }; const openAgent = Effect.fnUntraced(function* (openInput: { readonly operation: "create" | "resume"; @@ -3030,7 +3044,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( // A send-time set replaces the create-time set, so the workspace servers go only here and are // read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources. const turnMcpServers = { - ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), + ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy)), ...mcpServers, }; let starting = true; diff --git a/packages/provider-cursor/src/server/workspaceMcpServers.ts b/packages/provider-cursor/src/server/workspaceMcpServers.ts index f3e53b508e3b3..6cdfb98f5116a 100644 --- a/packages/provider-cursor/src/server/workspaceMcpServers.ts +++ b/packages/provider-cursor/src/server/workspaceMcpServers.ts @@ -83,6 +83,8 @@ function cursorProjectSlug(projectRoot: string): string { export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")(function* ( cwd: string, environment: NodeJS.ProcessEnv, + // The project file is the checkout's own; a restricted turn must not start its commands. + options: { readonly includeProject: boolean }, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -144,7 +146,7 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( const seen = new Set(); const servers: Record = {}; for (const file of [ - path.join(projectRoot, ".cursor", "mcp.json"), + ...(options.includeProject ? [path.join(projectRoot, ".cursor", "mcp.json")] : []), path.join(userHome, ".cursor", "mcp.json"), ]) { const contents = yield* readJsonc(file); From 7dd35d324db68c092ab5dec0fa7ea7659470c6b3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:45:25 -0800 Subject: [PATCH 051/190] fix(server): link codes and guest links require the access they hand out (#41742) Getting a link code through a linked environment now requires the scopes of the access level requested, and creating a guest link requires orchestration:read, in addition to access:write. The link dialog offers linking through another environment only when the session holds them. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.test.ts | 70 +++++++++++++++++++ .../server/src/peer/PeerClientPairing.test.ts | 32 --------- .../settings/LinkedEnvironmentsSettings.tsx | 14 +++- docs/internals/04_environment-auth.md | 11 ++- docs/internals/06_t3-connect.md | 4 +- docs/user/remote-access.md | 3 +- .../contracts/src/clientRpcPermissions.ts | 11 +++ 7 files changed, 107 insertions(+), 38 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 750ff136ac07d..15ddfb90b08a5 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,6 +355,76 @@ it.effect("pairs a client with a linked environment only for one that may hand o }).pipe(Effect.scoped), ); +it.effect("hands out a link code or a guest link only within what the session itself holds", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate + > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate, + ), + ); + let handled = 0; + const environmentId = EnvironmentId.make("environment-box"); + const threadId = ThreadId.make("thread-1"); + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.peerLinksPairLink, () => + Effect.sync(() => { + handled++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ), + group.toLayerHandler(WS_METHODS.guestShareCreate, () => + Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))), + ), + ); + const clientWith = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))), + ); + + // Managing access alone is not running agents or reading threads. + const manager = yield* clientWith([AuthAccessWriteScope]); + expect( + yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + expect( + yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + + const supervisor = yield* clientWith([ + AuthAccessWriteScope, + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + ]); + expect( + yield* supervisor[WS_METHODS.peerLinksPairLink]({ + environmentId, + access: "full-access", + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); + expect(handled).toBe(0); + + expect( + (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type, + ).toBe("unsupported"); + expect(handled).toBe(1); + yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit); + expect(handled).toBe(2); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts index 17a5df1cb75ff..8dacc53f7f07e 100644 --- a/apps/server/src/peer/PeerClientPairing.test.ts +++ b/apps/server/src/peer/PeerClientPairing.test.ts @@ -257,38 +257,6 @@ it.effect("pairs no client while Linked environments is off on either side", () ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); -it.effect("a full-access link gets a pairing code that links another environment to the box", () => - Effect.scoped( - Effect.gen(function* () { - const b = yield* serveBox(); - const a = yield* makeLaptop; - yield* linkTo(a.links, b, "full-access"); - const phone = yield* a.client([AuthAccessWriteScope]); - - const result = yield* a.pairing.requestForLink( - { environmentId: box.environmentId, access: "approval-required" }, - phone, - ); - if (result.type !== "credential") return yield* Effect.die(result); - expect(result).toMatchObject({ environmentId: box.environmentId, urls: [b.url] }); - - // A third environment links with it, at the access the code was minted for. - const desk = yield* Layer.build( - layerLinkingEnvironment(descriptorOf("environment-desk", "Desk")), - ); - const linked = yield* Context.get(desk, PeerLinks.PeerLinks).link({ - url: b.url, - pairingCode: result.credential, - access: "approval-required", - }); - expect(linked).toMatchObject({ - environmentId: box.environmentId, - access: "approval-required", - }); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - it.effect("a linked environment from before link pairing is never asked for one", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 5ab6debec7255..71afddaa33b32 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -329,8 +329,20 @@ export function LinkEnvironmentDialog({ const throughCandidate = prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null)); const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null); + // The environment holding the link refuses a level this client's session there does not hold. + const mayPairThrough = useAtomValue( + peerLinkEnvironment.pairLink.permissionAtom( + throughCandidate?.viaEnvironmentId ?? null, + throughCandidate === null + ? undefined + : { environmentId: throughCandidate.environmentId, access }, + ), + ); const through = - throughCandidate !== null && via !== null && !throughFailed.has(throughCandidate.environmentId) + throughCandidate !== null && + via !== null && + mayPairThrough && + !throughFailed.has(throughCandidate.environmentId) ? throughCandidate : null; const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open); diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 53c9f60d8f7c6..8b80c65860d60 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -8,8 +8,12 @@ model. ## Scoped sessions and delegation - **Narrowing only.** Pairing delegates a set of scopes. Exchanging a bootstrap credential can - narrow a grant, never widen it. Creating another pairing link requires both `access:write` and - every scope being delegated. Client labels and device metadata have no authorization role. + narrow a grant, never widen it. Client labels and device metadata have no authorization role. +- **`access:write` hands out what the session holds and revokes anything.** Every route that + returns a credential to the caller requires `access:write` and every scope that credential + carries: a pairing link, an MCP sign-in approval, a link code from a linked environment, and a + guest link (which reads a thread). Revoking is not capped by the caller's scopes. Admitting a + T3 Connect device is not delegation; see [T3 Connect](./06_t3-connect.md). - **Why the default grant includes management scopes.** `terminal:operate` and `orchestration:operate` already grant OS-user execution (which can invoke `t3 auth session issue`), so withholding access or relay management from the default grant would not be a real boundary. @@ -48,7 +52,8 @@ model. - **Peer-link client pairing.** Only a full-access peer link may mint a one-time client pairing on the linked environment (since full-access agents can already run `t3 auth pairing create`). The linked side enforces this itself, and the operation stays a human-triggered RPC/HTTP route rather - than an MCP tool. + than an MCP tool. The same route mints a code that links another environment at a chosen access + level, and the linking side's RPC requires the caller to hold that level's scopes. ### Reusable dev credential diff --git a/docs/internals/06_t3-connect.md b/docs/internals/06_t3-connect.md index 2962721830a86..dc60a5468b849 100644 --- a/docs/internals/06_t3-connect.md +++ b/docs/internals/06_t3-connect.md @@ -28,7 +28,9 @@ Deployment and Clerk configuration live in the [Connect setup runbook](../operat compromised relay signing key. Enabling `requireConnectDeviceApproval` shifts trust from the relay to approved DPoP key thumbprints: untrusted keys mint credentials that cannot be spent until someone with `access:write` approves the key, and revoking a key revokes all of its sessions and - pending credentials. + pending credentials. Approving admits a device already signed in to the owner's cloud account + and returns no credential to the approver, so `access:write` alone is enough, as it is for + turning the setting off. - **Anti-hijack and anti-SSRF rules.** Managed tunnels expose only the server's own loopback HTTP origin (ignoring caller-supplied origins). The relay refuses to relink an active environment ID under a different key until unlinked, resolves endpoints only from its own managed allocations, diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 051445f03eb07..bdcd2281ccd08 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -488,7 +488,8 @@ it needs no pairing code. A machine this app is not connected to, shown only because another environment links to it, can still be linked without a code when that link has full access: drop the plus on it and the environment holding the link gets the pairing code -from it. Your session on that environment must manage access there. The result +from it. Your session on that environment must manage access there and already +have the access you pick. The result is a separate link with the access you pick, listed and revocable on the linked machine like any other. Links still do not chain. diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b23b4650b20a9..eb61fff1c0abd 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -11,7 +11,9 @@ import { AuthSourceControlWriteScope, AuthTerminalOperateScope, type AuthEnvironmentScope, + mcpClientScopes, } from "./auth.ts"; +import { PeerLinkLinkPairingInput } from "./peerLink.ts"; import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts"; import { WS_METHODS } from "./rpc.ts"; @@ -106,6 +108,7 @@ export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; const decodePrepareThread = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput); const decodeStackedAction = Schema.decodeUnknownSync(GitRunStackedActionInput); +const decodeLinkPairing = Schema.decodeUnknownSync(PeerLinkLinkPairingInput); export function clientRpcRequiredScopes( method: string, @@ -124,6 +127,14 @@ export function clientRpcRequiredScopes( ) return [AuthSourceControlWriteScope, AuthOrchestrationReadScope]; } + // Handing out access takes holding it: the caller gets back a credential it can spend itself. + if (method === WS_METHODS.peerLinksPairLink && input !== undefined) { + const held = mcpClientScopes(decodeLinkPairing(input).access); + return [AuthAccessWriteScope, ...held]; + } + if (method === WS_METHODS.guestShareCreate) { + return [AuthAccessWriteScope, AuthOrchestrationReadScope]; + } return Object.hasOwn(CLIENT_GUARDED_RPC_SCOPES, method) ? [CLIENT_GUARDED_RPC_SCOPES[method as ClientGuardedRpcTag]] : []; From 2dd323463a300d82663eaa5df3e9b85b78d3eb7a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:48:05 -0800 Subject: [PATCH 052/190] fix(server): API request bodies have a 1 MiB default limit and tag scans stay linear (#41747) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/McpOAuth.test.ts | 22 +++++++++++++ apps/server/src/cloud/http.test.ts | 12 +++++++ apps/server/src/http.ts | 7 ++++ apps/server/src/server.ts | 1 + .../src/pullRequestMarkdown.test.ts | 21 ++++++++++++ .../client-runtime/src/pullRequestMarkdown.ts | 32 +++++++++++++++++-- packages/shared/src/htmlRender.test.ts | 21 ++++++++++-- packages/shared/src/htmlRender.ts | 12 ++++--- 8 files changed, 119 insertions(+), 9 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index f66d0b1c6e81c..c21b707bad889 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -27,6 +27,7 @@ import * as CloudLink from "../cloud/CloudLink.ts"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; @@ -75,6 +76,7 @@ const makeLayerRoutes = ( ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ).pipe( Layer.provideMerge(layerEnvironmentAuth), @@ -216,6 +218,26 @@ it.effect("derives discovery metadata from the origin the client reached", () => ), ); +it.effect("answers 413 to a body over the API limit", () => + withRoutes((handler) => + Effect.gen(function* () { + const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1); + for (const [path, contentType] of [ + ["/api/auth/browser-session", "application/json"], + ["/oauth/token", "application/x-www-form-urlencoded"], + ["/oauth/mcp/register", "application/json"], + ]) { + const init = { method: "POST", headers: { "content-type": contentType! } }; + expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413); + // A chunked body declares no length, so the reader itself has to stop. + const chunked = new Blob([body]).stream(); + const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit); + expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413); + } + }), + ), +); + it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 5115a27e63012..852be24a22200 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -31,6 +31,7 @@ import * as AuthHttp from "../auth/http.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; @@ -78,6 +79,7 @@ const layerConfig = Layer.effect( const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe( Layer.provide([AuthHttp.layer, ConnectHttp.layer]), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), Layer.provide(CloudLink.layer), Layer.provide(ServerSettings.ServerSettingsService.layerTest()), Layer.provide(EnvironmentKeys.layer), @@ -303,4 +305,14 @@ describe("link proof over a non-loopback transport", () => { expect(response.status).toBe(401); }), ); + + it.effect("answers 413 to a relay proof body over the API limit", () => + Effect.gen(function* () { + const { post } = yield* linkProofClient; + const payload = { proof: "x".repeat(ServerHttp.API_MAX_BODY_BYTES) }; + for (const path of ["/api/t3-connect/health", "/api/t3-connect/mint-credential"]) { + expect((yield* post(path, payload)).status, path).toBe(413); + } + }), + ); }); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 8a31a99287e38..493356998393a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -33,6 +33,7 @@ import { HttpServerRequest, HttpServerRespondable, } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { OtlpTracer, OtlpSerialization } from "effect/observability"; @@ -284,6 +285,12 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers }); }); +// The default body limit for API routes. Routes that take more set their own limit. +export const API_MAX_BODY_BYTES = 1024 * 1024; +export const layerApiBodyLimit = HttpRouter.middleware( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(API_MAX_BODY_BYTES)), +).layer; + export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { global: true, }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 26cea18609b93..b3c21d9918860 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -900,6 +900,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(ServerHttp.layerServerEnvironmentHttpApi), Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index 7d9d162d76a05..a397241775db6 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -190,6 +190,15 @@ describe("pull request body segmentation", () => { ]); }); + it.each([ + ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`], + ["a run of unclosed video tags", `${"