From 0229296df9f6972b510d20f339e4b364b943d113 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Fri, 16 Oct 2026 19:10:59 -0700 Subject: [PATCH 001/408] feat(codex): add Traex bridge provider preset --- .../Adapters/CodexAdapterV2.test.ts | 377 ++++++++++++++-- .../Adapters/CodexAdapterV2.ts | 17 +- .../src/provider/CodexInstallation.test.ts | 30 ++ apps/server/src/provider/CodexInstallation.ts | 10 +- .../src/provider/Drivers/CodexDriver.test.ts | 416 ++++++++++++++++++ .../src/provider/Drivers/CodexDriver.ts | 83 +++- .../provider/Drivers/CodexHomeLayout.test.ts | 53 +++ .../src/provider/Drivers/CodexHomeLayout.ts | 5 +- .../CodexTextGeneration.test.ts | 33 +- .../src/textGeneration/CodexTextGeneration.ts | 5 +- ...roviderInstanceDialog.environment.test.tsx | 266 +++++++++++ .../AddProviderInstanceDialog.logic.ts | 5 + .../settings/AddProviderInstanceDialog.tsx | 83 +++- docs/user/providers-codex.md | 11 + 14 files changed, 1301 insertions(+), 93 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 6e4a6494fb78..1b59ffb3a1dc 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1961,13 +1961,18 @@ describe("CodexAdapterV2 post-settle continuation", () => { Effect.void, onRequest: (method: string, params: unknown) => Effect.Effect = () => Effect.void, readChildMetadata?: Parameters[2], + runtimeOptions: Partial< + Pick + > & { readonly modelProvider?: string | null } = {}, ) => Effect.gen(function* () { + const { modelProvider = null, ...adapterRuntimeOptions } = runtimeOptions; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie); const continuationRequests: Array = []; + const configReadRequests: Array = []; const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = { open: (openInput) => Layer.build(CodexReplay.layerReplay(transcript)).pipe( @@ -1988,6 +1993,19 @@ describe("CodexAdapterV2 post-settle continuation", () => { (client) => ({ ...client, + raw: { + ...client.raw, + request: (method, params) => + method === "config/read" + ? Effect.sync(() => { + configReadRequests.push(params); + return { + config: { model_provider: modelProvider }, + origins: {}, + }; + }) + : client.raw.request(method, params), + }, request: (method, params) => onRequest(method, params).pipe( Effect.andThen(client.request(method, params)), @@ -2002,6 +2020,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, settings: DEFAULT_CODEX_SETTINGS, + ...adapterRuntimeOptions, environment: {}, clientFactory, crypto: yield* Crypto.Crypto, @@ -2071,6 +2090,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { serverConfig, events, continuationRequests, + configReadRequests, terminalEvents, subagentUpdates, hasPendingBackgroundWork, @@ -2078,6 +2098,98 @@ describe("CodexAdapterV2 post-settle continuation", () => { }; }); + it.effect.each([ + { setupMode: "existing" as const, resolved: true }, + { setupMode: "managed" as const, resolved: true }, + { setupMode: "managed" as const, resolved: false }, + ])( + "applies service tiers for $setupMode sessions with resolved runtime $resolved", + ({ setupMode, resolved }) => + Effect.gen(function* () { + const nativeThreadId = `tier-${setupMode}-${resolved}`; + const nativeTurnId = `${nativeThreadId}-turn`; + const prompt = "Run with the selected tier"; + const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }); + const entries = preamble.map((entry) => + entry.type === "expect_outbound" && entry.label === "turn/start" + ? { + ...entry, + frame: { + id: 3, + method: "turn/start", + params: { + threadId: nativeThreadId, + input: [{ type: "text", text: prompt }], + cwd: "/workspace", + model: "gpt-5.4", + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + summary: "detailed", + ...(setupMode === "existing" ? { serviceTier: "priority" } : {}), + }, + }, + } + : entry, + ); + const settings = { ...DEFAULT_CODEX_SETTINGS, setupMode }; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: nativeThreadId, + entries: [ + ...entries, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }), + undefined, + undefined, + undefined, + { + settings: resolved ? DEFAULT_CODEX_SETTINGS : settings, + ...(resolved + ? { + resolveRuntime: Effect.succeed({ + config: settings, + environment: {}, + revision: "test", + }), + } + : {}), + }, + ); + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`${nativeThreadId}-attempt`), + text: prompt, + }), + modelSelection: { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "serviceTier", value: "priority" }], + }, + }); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + it.effect.each(["supported", "unsupported", "invalid"] as const)( "delivers native history with %s app-server protocol", (response) => @@ -3161,56 +3273,220 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("resumes a provider thread without requesting or decoding its history", () => - Effect.scoped( + it.effect( + "loads an unloaded paginated thread with its destination provider before rollback", + () => Effect.gen(function* () { - const scenario = "codex-resume-metadata"; - const nativeThreadId = `native-${scenario}-thread`; + const nativeThreadId = "unloaded-rollback-thread"; const preamble = codexReplayPreamble({ nativeThreadId, - nativeTurnId: "unused-turn", - prompt: "unused-prompt", - }).slice(0, 5); - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...preamble, - { - type: "expect_outbound", - label: "thread/resume", - frame: { - id: 3, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, + nativeTurnId: "unused", + prompt: "unused", + }); + const revertedThread = codexReplayThreadResult({ nativeThreadId, forkedFromId: null }); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "unloaded-rollback", + entries: [ + ...preamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/read", + frame: { + id: 3, + method: "thread/read", + params: { threadId: nativeThreadId, includeTurns: false }, }, }, - }, - { - type: "emit_inbound", - label: "thread/resume", - frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - ], + { + type: "emit_inbound", + label: "thread/read", + frame: { + id: 3, + result: { + thread: { + id: nativeThreadId, + historyMode: "paginated", + status: { type: "notLoaded" }, + }, + }, + }, + }, + { + type: "expect_outbound", + label: "thread/resume", + frame: { + id: 4, + method: "thread/resume", + params: { + threadId: nativeThreadId, + modelProvider: "local_custom", + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, + }, + }, + { + type: "emit_inbound", + label: "thread/resume", + frame: { id: 4, result: revertedThread }, + }, + { + type: "expect_outbound", + label: "thread/turns/list", + frame: { + id: 5, + method: "thread/turns/list", + params: { + threadId: nativeThreadId, + cursor: null, + limit: 1, + sortDirection: "desc", + itemsView: "summary", + }, + }, + }, + { + type: "emit_inbound", + label: "thread/turns/list", + frame: { + id: 5, + result: { + data: [ + { id: "native-turn-second", items: [], status: "completed", error: null }, + ], + nextCursor: null, + }, + }, + }, + { + type: "expect_outbound", + label: "thread/revert", + frame: { + id: 6, + method: "thread/revert", + params: { threadId: nativeThreadId, beforeTurnId: "native-turn-second" }, + }, + }, + { + type: "emit_inbound", + label: "thread/revert", + frame: { id: 6, result: revertedThread }, + }, + ], + }), + undefined, + undefined, + undefined, + { modelProvider: "local_custom" }, + ); + const now = yield* DateTime.now; + const firstTurn = codexReplaySourceTurn({ + id: "first", + ordinal: 1, + nativeId: "native-turn-first", + providerThreadId: harness.providerThread.id, + now, }); - const harness = yield* makeCodexReplayHarness(transcript); - const resumed = yield* harness.runtime.resumeThread({ + const secondTurn = codexReplaySourceTurn({ + id: "second", + ordinal: 2, + nativeId: "native-turn-second", + providerThreadId: harness.providerThread.id, + now, + }); + const result = yield* harness.runtime.rollbackThread({ providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("unloaded-rollback"), + appRunOrdinal: 1, + providerTurn: firstTurn, + }, + providerThreadTurns: [firstTurn, secondTurn], }); - - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - assert.equal(resumed.status, "idle"); - assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); + assert.deepEqual(result.providerPayload, { ...revertedThread.thread, projectId: null }); + assert.equal(result.providerThread.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal( + result.providerThread.nativeConversationHeadRef?.nativeId, + "native-turn-first", + ); + assert.equal(result.providerThread.status, "idle"); + assert.deepEqual(harness.configReadRequests, [{ cwd: "/workspace", includeLayers: false }]); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), + ); + + it.effect.each([ + { configured: null, expected: "openai" }, + { configured: "local_custom", expected: "local_custom" }, + { configured: "openai_token_sharing", expected: "openai_token_sharing" }, + ])( + "resumes with destination provider $expected without decoding history", + ({ configured, expected }) => + Effect.scoped( + Effect.gen(function* () { + const scenario = "codex-resume-metadata"; + const nativeThreadId = `native-${scenario}-thread`; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5); + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...preamble, + { + type: "expect_outbound", + label: "thread/resume", + frame: { + id: 3, + method: "thread/resume", + params: { + threadId: nativeThreadId, + modelProvider: expected, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, + }, + }, + { + type: "emit_inbound", + label: "thread/resume", + frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + { modelProvider: configured }, + ); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, cwd: "/destination-project" }, + }); + + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal(resumed.status, "idle"); + assert.deepEqual(harness.configReadRequests, [ + { cwd: "/destination-project", includeLayers: false }, + ]); + assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), ); it.effect.each( @@ -3270,6 +3546,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { const nativeThreadId = "saved-thread"; const params = { threadId: nativeThreadId, + modelProvider: "openai", excludeTurns: true, cwd: CODEX_TEST_RUNTIME_POLICY.cwd, model: CODEX_TEST_MODEL_SELECTION.model, @@ -3395,6 +3672,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { method: "thread/resume", params: { threadId: nativeThreadId, + modelProvider: "openai", excludeTurns: true, config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, @@ -8266,9 +8544,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect( - "falls back to fork-local thread/revert on paginated history when the source turn lacks a native reference", - () => + it.effect.each([ + { configured: null, expected: "openai" }, + { configured: "local_custom", expected: "local_custom" }, + { configured: "openai_token_sharing", expected: "openai_token_sharing" }, + ])( + "forks with destination provider $expected and reverts fork-local paginated history", + ({ configured, expected }) => Effect.gen(function* () { const nativeThreadId = "fallback-source-thread"; const forkThreadId = "fallback-fork-thread"; @@ -8287,7 +8569,11 @@ describe("CodexAdapterV2 post-settle continuation", () => { frame: { id: 3, method: "thread/fork", - params: { threadId: nativeThreadId, config: CodexAdapterV2.CODEX_THREAD_CONFIG }, + params: { + threadId: nativeThreadId, + modelProvider: expected, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, }, }, { @@ -8374,6 +8660,8 @@ describe("CodexAdapterV2 post-settle continuation", () => { Effect.sync(() => { outbound.push(method); }), + undefined, + { modelProvider: configured }, ); const now = yield* DateTime.now; const firstTurn = codexReplaySourceTurn({ @@ -8431,7 +8719,11 @@ describe("CodexAdapterV2 post-settle continuation", () => { frame: { id: 3, method: "thread/fork", - params: { threadId: nativeThreadId, config: CodexAdapterV2.CODEX_THREAD_CONFIG }, + params: { + threadId: nativeThreadId, + modelProvider: "openai", + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, }, }, { @@ -8538,6 +8830,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { params: { threadId: nativeThreadId, lastTurnId: "native-turn-first", + modelProvider: "openai", config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 19d1e7b7ffe2..fb70deb01298 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1784,6 +1784,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ); const now = yield* DateTime.now; + const readModelProvider = (runtimePolicy = input.runtimePolicy) => + ensureInitialized.pipe( + Effect.andThen( + client.raw.request("config/read", { + cwd: runtimePolicy.cwd, + includeLayers: false, + }), + ), + Effect.flatMap(Schema.decodeUnknownEffect(CodexSchema.V2ConfigReadResponse)), + Effect.map((response) => response.config.model_provider ?? "openai"), + ); const session = providerSession({ providerSessionId: input.providerSessionId, providerInstanceId: adapterOptions.instanceId, @@ -6193,7 +6204,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( hasT3Mcp: mcpSession !== undefined, browserToolsAvailable: mcpSession?.browserToolsAvailable ?? true, deviceToolsAvailable: mcpSession?.capabilities?.has("device") ?? false, - omitServiceTier: adapterOptions.resolveRuntime !== undefined, + omitServiceTier: + (resolvedRuntime?.config ?? adapterOptions.settings).setupMode === "managed", ...(turnInput.appContext === undefined ? {} : { appContext: turnInput.appContext }), }); yield* Ref.update(pendingRootTurns, (current) => { @@ -6491,6 +6503,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // excludeTurns is not in the generated request schema yet. const resume = client.raw.request("thread/resume", { threadId: nativeThreadId, + modelProvider: yield* readModelProvider(threadInput.runtimePolicy), excludeTurns: true, ...codexThreadRuntimeParams({ mcpSession: yield* readMcpSession( @@ -7210,6 +7223,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (!loaded) { yield* client.raw.request("thread/resume", { threadId, + modelProvider: yield* readModelProvider(), excludeTurns: true, ...codexThreadRuntimeParams({ mcpSession: yield* readMcpSession(threadInput.providerThread.appThreadId), @@ -7257,6 +7271,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.andThen( client.request("thread/fork", { threadId, + modelProvider: yield* readModelProvider(threadInput.runtimePolicy), ...(boundary.lastTurnId === undefined ? {} : { lastTurnId: boundary.lastTurnId }), diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index 54cc2aeb41c1..90cc6c6dde1b 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -167,6 +167,36 @@ it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])( expect((yield* h.installation.state).source).toBe("local"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect.each([true, false])( + "acquires only the managed runtime when requested with managed installation %s", + (managedInstalled) => + Effect.gen(function* () { + const first = yield* makeHarness(); + if (managedInstalled) { + yield* first.installation.start; + expect((yield* terminalState(first.installation)).phase).toBe("succeeded"); + } + const h = yield* makeHarness({ baseDir: first.baseDir, local: { version: "0.156.2" } }); + expect(yield* h.installation.acquire().pipe(Effect.scoped)).toMatchObject({ + source: "local", + executablePath: h.localBinaryPath, + version: "0.156.2", + }); + const managed = h.installation.acquire({ managedOnly: true }).pipe(Effect.scoped); + if (managedInstalled) { + expect(yield* managed).toMatchObject({ + source: "managed", + executablePath: `${h.baseDir}/tools/codex/0.156.1/bin/codex`, + version: "0.156.1", + }); + } else { + expect((yield* Effect.flip(managed)).detail).toBe( + "Codex is not installed in T3 Code. Install it to continue.", + ); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect.each([ { version: "0.128.9" }, { version: "0.145.0" }, diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 31b62f0e26b1..ec89f8979213 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -124,7 +124,9 @@ export interface CodexExecutable { interface CodexInstallationService { readonly managedDirectory: string; readonly resolve: () => Effect.Effect; - readonly acquire: () => Effect.Effect; + readonly acquire: (options?: { + readonly managedOnly?: boolean; + }) => Effect.Effect; readonly start: Effect.Effect; readonly cancel: ( operationId: string, @@ -287,10 +289,12 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function wrapFailure("resolve", "Codex is not installed in T3 Code. Install it to continue."), ), ); - const acquire = Effect.fn("CodexInstallation.acquire")(function* () { + const acquire = Effect.fn("CodexInstallation.acquire")(function* (options?: { + readonly managedOnly?: boolean; + }) { return yield* Effect.acquireRelease( gate.withPermit( - resolve().pipe( + (options?.managedOnly === true ? resolveManaged() : resolve()).pipe( Effect.tap(() => Effect.sync(() => { leases += 1; diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 51301ef43c50..697d903d2876 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -96,6 +96,422 @@ const noSpawn = ChildProcessSpawner.make(() => const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); it.layer(layerTest)("CodexDriver", (it) => { + it.effect.each([true, false])( + "keeps the instance PATH boundary when host Codex exists and managed installation is %s", + (managedInstalled) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-instance-path-" }); + const hostBin = NodePath.join(root, "host-bin"); + const instanceBin = NodePath.join(root, "instance-bin"); + yield* fs.makeDirectory(hostBin); + yield* fs.makeDirectory(instanceBin); + const hostBinary = NodePath.join(hostBin, "codex"); + yield* fs.writeFileString(hostBinary, "#!/bin/sh\nprintf 'codex-cli 0.156.2\\n'\n", { + mode: 0o755, + }); + const managedDirectory = NodePath.join(root, "tools", "codex"); + const versionDirectory = NodePath.join(managedDirectory, "0.156.1"); + const managedBinary = NodePath.join(versionDirectory, "bin", "codex"); + if (managedInstalled) { + for (const relative of ["bin/codex", "bin/codex-code-mode-host", "codex-path/rg"]) { + const file = NodePath.join(versionDirectory, relative); + yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "#!/bin/sh\n", { mode: 0o755 }); + } + yield* fs.writeFileString( + NodePath.join(versionDirectory, "codex-package.json"), + JSON.stringify({ + layoutVersion: 1, + version: "0.156.1", + target: "test-target", + entrypoint: "bin/codex", + }), + ); + yield* fs.writeFileString( + NodePath.join(versionDirectory, ".install-complete.json"), + JSON.stringify({ version: "0.156.1", target: "test-target", sha256: "test-sha" }), + ); + yield* fs.writeFileString( + NodePath.join(managedDirectory, "active.json"), + '{"version":"0.156.1"}', + ); + } + const installation = yield* CodexInstallation.makeCodexInstallation({ baseDir: root }).pipe( + Effect.provideService(HostProcess.Environment, { PATH: hostBin }), + ); + expect(yield* installation.acquire().pipe(Effect.scoped)).toMatchObject({ + source: "local", + executablePath: hostBinary, + }); + const commands: Array = []; + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("isolated-path"), + displayName: "Instance PATH", + enabled: true, + environment: [{ name: "PATH", value: instanceBin, sensitive: false }], + config: { ...CodexDriver.defaultConfig(), homePath: NodePath.join(root, "home") }, + }).pipe( + Effect.provideService(CodexInstallation.CodexInstallation, installation), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) commands.push(command.command); + return Effect.fail( + PlatformError.badArgument({ + module: "ChildProcessSpawner", + method: "spawn", + description: "Fixture records the selected executable", + }), + ); + }), + ), + ); + const snapshot = yield* instance.snapshot.refresh; + expect(snapshot.installed).toBe(false); + expect(snapshot.status).toBe("error"); + expect([...new Set(commands)]).toEqual([managedInstalled ? managedBinary : "codex"]); + }).pipe(Effect.scoped), + { skip: windowsHost }, + ); + + it.effect.skipIf(windowsHost)( + "uses a later installation without recreating an existing instance and leases only active operations", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-later-install-" }); + const binDir = NodePath.join(root, "bin"); + yield* fs.makeDirectory(binDir); + const executablePath = NodePath.join(root, "packages", "standalone", "bin", "codex"); + yield* fs.makeDirectory(NodePath.dirname(executablePath), { recursive: true }); + yield* fs.writeFileString( + executablePath, + [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + "const args = process.argv.slice(2);", + 'if (args.includes("mcp")) { process.stdout.write("[]"); process.exit(0); }', + 'if (args.includes("exec")) {', + ' fs.writeFileSync(args[args.indexOf("--output-last-message") + 1], JSON.stringify({ title: "Installed runtime title" }));', + ' process.stdin.resume(); process.stdin.on("end", () => process.exit(0));', + "} else {", + ' require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => {', + " const { id, method } = JSON.parse(line);", + " if (id === undefined) return;", + " const results = {", + ' initialize: { userAgent: "codex/0.156.1", codexHome: process.env.CODEX_HOME, platformFamily: "unix", platformOs: "macos" },', + ' "account/read": { account: { type: "apiKey" }, requiresOpenaiAuth: false },', + ' "model/list": { data: [], nextCursor: null },', + ' "skills/list": { data: [] },', + ' "account/rateLimits/read": { rateLimits: {} },', + ' "account/rateLimitResetCredit/consume": { outcome: "nothingToReset" },', + " };", + ' process.stdout.write(JSON.stringify({ id, result: results[method] }) + "\\n");', + " });", + "}", + ].join("\n"), + ); + yield* fs.chmod(executablePath, 0o755); + const installation = yield* CodexInstallation.CodexInstallation; + let available = false; + let leases = 0; + let idle = Deferred.makeUnsafe(); + yield* Deferred.succeed(idle, undefined); + const instanceId = ProviderInstanceId.make("later-install"); + const instance = yield* CodexDriver.create({ + instanceId, + displayName: "Existing custom provider", + enabled: true, + environment: [{ name: "PATH", value: binDir, sensitive: false }], + config: { + ...CodexDriver.defaultConfig(), + homePath: NodePath.join(root, "home"), + launchArgs: '-c model_provider="traex"', + }, + }).pipe( + Effect.provide(CodexAdapterV2.layerAppServerClientFactory), + Effect.provideService(CodexInstallation.CodexInstallation, { + ...installation, + acquire: (options) => + Effect.gen(function* () { + expect(options).toEqual({ managedOnly: true }); + if (!available) + return yield* new CodexInstallation.CodexInstallationError({ + operation: "resolve", + detail: "No Codex installation is available.", + }); + return yield* Effect.acquireRelease( + Effect.sync(() => { + if (leases === 0) idle = Deferred.makeUnsafe(); + leases += 1; + return { + executablePath, + managedVersionDirectory: root, + source: "managed" as const, + version: "0.156.1", + }; + }), + () => + Effect.sync(() => { + leases -= 1; + }).pipe( + Effect.flatMap(() => + leases === 0 ? Deferred.succeed(idle, undefined) : Effect.void, + ), + ), + ); + }), + }), + ); + expect((yield* instance.snapshot.refresh).installed).toBe(false); + expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull(); + expect(leases).toBe(0); + + available = true; + const snapshot = yield* instance.snapshot.refresh; + expect(snapshot).toMatchObject({ installed: true, status: "ready", version: "0.156.1" }); + expect(leases).toBe(0); + expect((yield* instance.snapshot.resolveMaintenance({ fresh: true })).update).toMatchObject( + { + executable: executablePath, + args: ["update"], + }, + ); + yield* Deferred.await(idle); + expect(leases).toBe(0); + const title = yield* instance.textGeneration.generateThreadTitle({ + cwd: root, + message: "Use the new installation", + modelSelection: { instanceId, model: "gpt-5.4" }, + }); + expect(title).toEqual({ title: "Installed runtime title" }); + expect(leases).toBe(0); + expect((yield* instance.snapshotForCwd!(root)).installed).toBe(true); + expect(leases).toBe(0); + expect(yield* instance.consumeResetCredit!()).toBe("nothingToReset"); + expect(leases).toBe(0); + yield* Effect.gen(function* () { + const session = yield* instance.orchestrationAdapter.openSession({ + threadId: ThreadId.make("later-install-thread"), + providerSessionId: ProviderSessionId.make("later-install-session"), + modelSelection: { instanceId, model: "gpt-5.4" }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: root, + }), + }); + expect(session.providerSession.providerInstanceId).toBe(instanceId); + expect(leases).toBe(1); + }).pipe(Effect.scoped); + expect(leases).toBe(0); + }).pipe(Effect.scoped), + ); + + it.effect.each([ + { + name: "missing default command", + binaryPath: "codex", + onPath: false, + available: true, + enabled: true, + acquires: 1, + }, + { + name: "empty default command", + binaryPath: "", + onPath: false, + available: true, + enabled: true, + acquires: 1, + }, + { + name: "PATH command", + binaryPath: "codex", + onPath: true, + available: true, + enabled: true, + acquires: 0, + }, + { + name: "explicit path", + binaryPath: "/custom/bin/codex", + onPath: false, + available: true, + enabled: true, + acquires: 0, + }, + { + name: "explicit command", + binaryPath: "custom-codex", + onPath: false, + available: true, + enabled: true, + acquires: 0, + }, + { + name: "unavailable installation", + binaryPath: "codex", + onPath: false, + available: false, + enabled: true, + acquires: 1, + }, + { + name: "disabled provider", + binaryPath: "codex", + onPath: false, + available: true, + enabled: false, + acquires: 0, + }, + ])( + "resolves an existing-mode executable for $name", + (fixture) => + Effect.gen(function* () { + let acquisitions = 0; + let leases = 0; + yield* Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-existing-" }); + const binDir = NodePath.join(root, "bin"); + yield* fs.makeDirectory(binDir); + if (fixture.onPath) { + const command = NodePath.join(binDir, windowsHost ? "codex.exe" : "codex"); + yield* fs.writeFileString(command, "#!/bin/sh\n"); + yield* fs.chmod(command, 0o755); + } + const acquiredPath = NodePath.join(root, "installed", "codex"); + const installation = yield* CodexInstallation.CodexInstallation; + const launches: Array< + Parameters[0] + > = []; + const commands: Array = []; + const homePath = NodePath.join(root, "shared"); + const shadowHomePath = NodePath.join(root, "shadow"); + const launchArgs = '-c model_provider="traex"'; + const instanceId = ProviderInstanceId.make("existing-runtime"); + const instance = yield* CodexDriver.create({ + instanceId, + displayName: "Existing runtime", + enabled: fixture.enabled, + environment: [ + { name: "PATH", value: binDir, sensitive: false }, + { name: "TRAEX_TOKEN", value: "custom-token", sensitive: true }, + ], + config: { + ...CodexDriver.defaultConfig(), + binaryPath: fixture.binaryPath, + homePath, + shadowHomePath, + launchArgs, + }, + }).pipe( + Effect.provideService(CodexInstallation.CodexInstallation, { + ...installation, + acquire: (options) => + Effect.gen(function* () { + expect(options).toEqual({ managedOnly: true }); + acquisitions += 1; + if (!fixture.available) + return yield* new CodexInstallation.CodexInstallationError({ + operation: "resolve", + detail: "No Codex installation is available.", + }); + return yield* Effect.acquireRelease( + Effect.sync(() => { + leases += 1; + return { + executablePath: acquiredPath, + managedVersionDirectory: root, + source: "managed" as const, + version: "0.156.1", + }; + }), + () => + Effect.sync(() => { + leases -= 1; + }), + ); + }), + }), + Effect.provideService(CodexAdapterV2.CodexAppServerClientFactory, { + open: (launch) => + Effect.sync(() => launches.push(launch)).pipe( + Effect.andThen(Effect.die("Fixture records the requested session launch")), + ), + }), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) commands.push(command); + return Effect.fail( + PlatformError.badArgument({ + module: "ChildProcessSpawner", + method: "spawn", + description: "Fixture records the requested command", + }), + ); + }), + ), + ); + yield* instance.snapshot.refresh; + expect(leases).toBe(0); + if (!fixture.enabled) { + expect((yield* instance.snapshot.getSnapshot).enabled).toBe(false); + expect(commands).toEqual([]); + return; + } + const expectedBinary = + fixture.acquires && fixture.available ? acquiredPath : fixture.binaryPath || "codex"; + const beforeSession = acquisitions; + yield* instance.orchestrationAdapter + .openSession({ + threadId: ThreadId.make("existing-thread"), + providerSessionId: ProviderSessionId.make("existing-session"), + modelSelection: { instanceId, model: "gpt-5.4" }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: root, + }), + }) + .pipe(Effect.scoped, Effect.exit); + expect(launches).toHaveLength(1); + expect(launches[0]).toMatchObject({ + settings: { binaryPath: expectedBinary, homePath: shadowHomePath, launchArgs }, + environment: { TRAEX_TOKEN: "custom-token", PATH: binDir }, + }); + expect(acquisitions - beforeSession).toBe(fixture.acquires); + expect(leases).toBe(0); + const beforeRefresh = acquisitions; + const snapshot = yield* instance.snapshot.refresh; + expect(snapshot.installed).toBe(false); + expect(acquisitions - beforeRefresh).toBe(fixture.acquires); + expect(leases).toBe(0); + yield* instance.textGeneration + .generateThreadTitle({ + cwd: root, + message: "Add a test", + modelSelection: { instanceId, model: "gpt-5.4" }, + }) + .pipe(Effect.exit); + expect(commands.at(-1)?.args).toContain("exec"); + expect(commands.map((command) => command.command)).toEqual( + commands.map(() => expectedBinary), + ); + expect(commands.at(-1)?.options.env).toMatchObject({ + CODEX_HOME: shadowHomePath, + TRAEX_TOKEN: "custom-token", + }); + expect(leases).toBe(0); + }).pipe(Effect.scoped); + expect(leases).toBe(0); + }).pipe(Effect.scoped), + { skip: windowsHost }, + ); + it.effect("disconnect refreshes a restored managed account while its auth flow is idle", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("restored-managed-account"); diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 2388213eed30..554c6d286f2c 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -1,9 +1,11 @@ import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; +import { resolveCommandPath } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import type { CodexEffectiveRuntime } from "../CodexManagedRuntime.ts"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; @@ -126,6 +128,9 @@ export const CodexDriver: ProviderDriver executable.executablePath), + Effect.catchTags({ CodexInstallationError: () => Effect.succeed(binaryPath) }), + ) + : binaryPath; + return { + config: { ...effectiveConfig, binaryPath: executablePath }, + environment: processEnv, + revision: executablePath, + } satisfies CodexEffectiveRuntime; + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, pathService), + ); const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( - resolveProviderMaintenanceCapabilitiesEffect( - makeCodexMaintenanceResolver(homeLayout.sharedHomePath), - { - binaryPath: effectiveConfig.binaryPath, - env: processEnv, - }, - ).pipe( + resolveRuntime.pipe( + Effect.flatMap((runtime) => + resolveProviderMaintenanceCapabilitiesEffect( + makeCodexMaintenanceResolver(homeLayout.sharedHomePath), + { + binaryPath: runtime.config.binaryPath, + env: runtime.environment, + }, + ), + ), + Effect.scoped, Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, pathService), @@ -175,7 +203,7 @@ export const CodexDriver: ProviderDriver snapshot.applyUsageLimits(update) }, + { onUsageLimits: (update) => snapshot.applyUsageLimits(update), resolveRuntime }, ).pipe( Effect.mapError( (cause) => @@ -193,7 +221,12 @@ export const CodexDriver: ProviderDriver + checkCodexProviderStatus(runtime.config, undefined, runtime.environment), + ), + Effect.scoped, + ), currentCatalog, (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), { concurrent: true }, @@ -242,19 +275,26 @@ export const CodexDriver: ProviderDriver value.models)), + resolveRuntime, ); const snapshotForCwd = (cwd: string) => !effectiveConfig.enabled ? snapshot.getSnapshot : Effect.all([ snapshot.getSnapshot, - probeCodexSkillsForCwd({ - binaryPath: effectiveConfig.binaryPath, - homePath: effectiveConfig.homePath, - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), - cwd, - environment: processEnv, - }).pipe( + resolveRuntime.pipe( + Effect.flatMap((runtime) => + probeCodexSkillsForCwd({ + binaryPath: runtime.config.binaryPath, + homePath: runtime.config.homePath, + launchArgs: resolveCodexLaunchArgs( + runtime.config.launchArgs, + runtime.environment, + ), + cwd, + environment: runtime.environment, + }), + ), Effect.scoped, Effect.timeout("20 seconds"), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -284,12 +324,13 @@ export const CodexDriver: ProviderDriver Effect.gen(function* () { + const runtime = yield* resolveRuntime; const { client } = yield* withCodexAppServerClient({ - binaryPath: effectiveConfig.binaryPath, - homePath: effectiveConfig.homePath, - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), + binaryPath: runtime.config.binaryPath, + homePath: runtime.config.homePath, + launchArgs: resolveCodexLaunchArgs(runtime.config.launchArgs, runtime.environment), cwd: process.cwd(), - environment: processEnv, + environment: runtime.environment, }); const response = yield* client.request("account/rateLimitResetCredit/consume", { idempotencyKey, diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts index 5323b6a26673..3e514276a678 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts @@ -14,6 +14,7 @@ import { resolveCodexHomeLayout, } from "./CodexHomeLayout.ts"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import * as HostProcess from "@t3tools/shared/HostProcess"; const decodeCodexSettingsValue = Schema.decodeSync(CodexSettings); const decodeCodexSettings = (input: { @@ -85,6 +86,58 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { }); describe("materializeCodexShadowHome", () => { + it.effect("creates a configured direct home and preserves it across retries", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* makeTempDir("t3code-codex-direct-"); + const homePath = path.join(root, "nested", "home"); + const layout = yield* resolveCodexHomeLayout(decodeCodexSettings({ homePath })); + + yield* materializeCodexShadowHome(layout); + expect((yield* fileSystem.stat(homePath)).type).toBe("Directory"); + yield* fileSystem.writeFileString(path.join(homePath, "auth.json"), "private auth"); + yield* materializeCodexShadowHome(layout); + expect(yield* fileSystem.readFileString(path.join(homePath, "auth.json"))).toBe( + "private auth", + ); + }), + ); + + it.effect("leaves the implicit default home for Codex to initialize", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* makeTempDir("t3code-codex-default-"); + const layout = yield* resolveCodexHomeLayout(decodeCodexSettings({})).pipe( + Effect.provideService(HostProcess.HomeDirectory, root), + ); + + yield* materializeCodexShadowHome(layout); + expect(yield* fileSystem.exists(path.join(root, ".codex"))).toBe(false); + }), + ); + + it.effect("reports a filesystem error when a direct home is a file", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const root = yield* makeTempDir("t3code-codex-direct-error-"); + const homePath = path.join(root, "home"); + yield* writeTextFile(homePath, "not a directory"); + const layout = yield* resolveCodexHomeLayout(decodeCodexSettings({ homePath })); + + const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "CodexShadowHomeFileSystemError", + operation: "makeDirectory", + path: homePath, + sharedHomePath: homePath, + effectiveHomePath: homePath, + cause: expect.any(PlatformError.PlatformError), + }); + }), + ); + it.effect.skipIf(!symlinksSupported)( "materializes a shadow home with shared state links and private auth", () => diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts index 9d4410da9843..3b693594a7db 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts @@ -320,10 +320,9 @@ const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsP export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* ( layout: CodexHomeLayout, ) { - if (layout.mode !== "authOverlay") return; const effectiveHomePath = layout.effectiveHomePath; if (!effectiveHomePath) return; - if (layout.sharedHomePath === effectiveHomePath) { + if (layout.mode === "authOverlay" && layout.sharedHomePath === effectiveHomePath) { return yield* new CodexShadowHomePathConflictError({ sharedHomePath: layout.sharedHomePath, effectiveHomePath, @@ -347,6 +346,8 @@ export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome" }), ); + if (layout.mode === "direct") return yield* makeDirectory(effectiveHomePath); + yield* Effect.all( [ makeDirectory(layout.sharedHomePath), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 7eab8ee7472d..ffb935512ad1 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -140,7 +140,7 @@ function withFakeCodexEnv( launchArgs?: string; environment?: NodeJS.ProcessEnv; models?: ReadonlyArray; - managedRuntime?: boolean; + resolvedRuntime?: "managed" | "existing"; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, ) { @@ -148,7 +148,11 @@ function withFakeCodexEnv( const fs = yield* FileSystem.FileSystem; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); const codexPath = yield* makeFakeCodexBinary(tempDir, input); - const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs }); + const config = decodeCodexSettings({ + binaryPath: codexPath, + launchArgs: input.launchArgs, + setupMode: input.resolvedRuntime ?? "existing", + }); const textGeneration = yield* makeCodexTextGeneration( config, input.environment === undefined ? undefined : { ...process.env, ...input.environment }, @@ -160,7 +164,7 @@ function withFakeCodexEnv( capabilities: null, })), ), - input.managedRuntime + input.resolvedRuntime ? Effect.succeed({ config, environment: input.environment ?? process.env, @@ -249,11 +253,32 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("preserves a service tier when an existing runtime resolves its executable", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Resolved existing runtime" }), + resolvedRuntime: "existing", + requireServiceTier: "priority", + }, + (textGeneration) => + Effect.gen(function* () { + const title = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Resolve the existing executable", + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "serviceTier", value: "priority" }, + ]), + }); + expect(title).toEqual({ title: "Resolved existing runtime" }); + }), + ), + ); + it.effect("omits a persisted service tier for managed ChatGPT text generation", () => withFakeCodexEnv( { output: JSON.stringify({ subject: "Update project", body: "" }), - managedRuntime: true, + resolvedRuntime: "managed", forbidArg: 'service_tier="priority"', }, (textGeneration) => diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 6ee03420b7ab..995c51671056 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -263,7 +263,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func const reasoningEffort = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? DEFAULT_TEXT_GENERATION_REASONING_EFFORT; - const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection); + const serviceTier = + effectiveConfig.setupMode === "managed" + ? undefined + : getCodexServiceTierOptionValue(modelSelection); const binary = effectiveConfig.binaryPath || "codex"; const env = { ...effectiveEnvironment, diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx index e4aba048bb6f..4fb7968abc79 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx @@ -52,6 +52,12 @@ vi.mock("../../state/session", async (importOriginal) => { vi.mock("../ui/toast", () => ({ toastManager: { add: actions.toast } })); import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog"; +import { + deriveProviderSettingsFields, + nextProviderConfigWithFieldValue, + type SettingsFormDefinition, +} from "./ProviderSettingsForm"; +import { tokenizeCliArgs } from "@t3tools/shared/cliArgs"; const remoteEnvironmentId = EnvironmentId.make("remote-device"); const preparedAgent: AcpRegistrySearchAgent = { @@ -194,6 +200,266 @@ describe("AddProviderInstanceDialog environment routing", () => { expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId); }); + it("persists a Traex preset as an isolated Codex instance in the selected environment", async () => { + settingsHooks.read.mockReturnValue({ + providerInstances: { codex_traex: { driver: "codex", enabled: true } }, + }); + let tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + + expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId); + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "codex_traex_2", + instance: { + driver: "codex", + enabled: true, + displayName: "Traex", + config: { + setupMode: "existing", + homePath: "~/.codex-t3/traex/codex_traex_2", + launchArgs: expect.any(String), + }, + }, + }); + const launchArgs: unknown = settingsHooks.mutate.mock.calls[0]?.[0]?.instance.config.launchArgs; + if (typeof launchArgs !== "string") throw new Error("Missing persisted launch arguments."); + const args = tokenizeCliArgs(launchArgs); + expect(args).toContain('model_provider="traex"'); + expect(args).toContainEqual(expect.stringContaining('base_url="http://127.0.0.1:8317/v1"')); + expect(args).toContainEqual(expect.stringContaining("cat ~/.traex-bridge/api-key")); + expect(args.join(" ")).not.toContain("model_catalog_url"); + expect(args.join(" ")).not.toContain("features.api_key_model_discovery"); + }); + + it.each([ + { name: "default home", editConfig: false, homePath: undefined }, + { name: "another config field", editConfig: true, homePath: undefined }, + { name: "custom home", editConfig: true, homePath: "~/.traex-personal" }, + ])("preserves isolation after changing the Traex ID with $name", async (fixture) => { + let tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + if (fixture.editConfig) { + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + const configuration = visitElements( + tree, + (element) => element.props.idPrefix === "add-provider-codex", + ); + (configuration!.props.onChange as (value: Record) => void)({ + ...(configuration!.props.value as Record), + binaryPath: "/opt/codex", + ...(fixture.homePath === undefined ? {} : { homePath: fixture.homePath }), + }); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + } + const instanceId = visitElements( + tree, + (element) => element.props.id === "add-provider-instance-id", + ); + (instanceId!.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "traex_custom" }, + }); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "traex_custom", + instance: { + driver: "codex", + enabled: true, + displayName: "Traex", + config: { + setupMode: "existing", + homePath: fixture.homePath ?? "~/.codex-t3/traex/traex_custom", + launchArgs: expect.any(String), + ...(fixture.editConfig ? { binaryPath: "/opt/codex" } : {}), + }, + }, + }); + }); + + it("derives the Traex home from the final ID after clearing a custom home", async () => { + let tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + let configuration = visitElements( + tree, + (element) => element.props.idPrefix === "add-provider-codex", + ); + const homeField = deriveProviderSettingsFields( + configuration!.props.definition as SettingsFormDefinition, + ).find((field) => field.key === "homePath"); + if (!homeField) throw new Error("Missing home path field."); + (configuration!.props.onChange as (value: Record | undefined) => void)( + nextProviderConfigWithFieldValue(configuration!.props.value, homeField, "~/.traex-personal"), + ); + tree = render(); + configuration = visitElements( + tree, + (element) => element.props.idPrefix === "add-provider-codex", + ); + (configuration!.props.onChange as (value: Record | undefined) => void)( + nextProviderConfigWithFieldValue(configuration!.props.value, homeField, ""), + ); + tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + const instanceId = visitElements( + tree, + (element) => element.props.id === "add-provider-instance-id", + ); + (instanceId!.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "traex_final" }, + }); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "traex_final", + instance: { + driver: "codex", + enabled: true, + displayName: "Traex", + config: { + setupMode: "existing", + homePath: "~/.codex-t3/traex/traex_final", + launchArgs: expect.any(String), + }, + }, + }); + }); + + it("preserves the edited Traex draft after returning to provider selection", async () => { + let tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + const label = visitElements(tree, (element) => element.props.id === "add-provider-label"); + (label!.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "Personal Traex" }, + }); + tree = render(); + const instanceId = visitElements( + tree, + (element) => element.props.id === "add-provider-instance-id", + ); + (instanceId!.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "traex_personal" }, + }); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + const configuration = visitElements( + tree, + (element) => element.props.idPrefix === "add-provider-codex", + ); + (configuration!.props.onChange as (value: Record) => void)({ + ...(configuration!.props.value as Record), + binaryPath: "/opt/codex-personal", + homePath: "~/.traex-personal", + launchArgs: "--profile personal", + }); + tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "traex_personal", + instance: { + driver: "codex", + enabled: true, + displayName: "Personal Traex", + config: { + setupMode: "existing", + binaryPath: "/opt/codex-personal", + homePath: "~/.traex-personal", + launchArgs: "--profile personal", + }, + }, + }); + }); + + it("restores the manual Codex draft after choosing Traex and switching back", async () => { + let tree = render(); + (findByChildren(tree, "Configure manually").props.onClick as () => void)(); + tree = render(); + const label = visitElements(tree, (element) => element.props.id === "add-provider-label"); + (label!.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "Work" }, + }); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + const configuration = visitElements( + tree, + (element) => element.props.idPrefix === "add-provider-codex", + ); + (configuration!.props.onChange as (value: Record) => void)({ + binaryPath: "/opt/codex", + homePath: "~/.codex-work", + }); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Use Traex").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); + const group = visitElements( + tree, + (element) => element.props["aria-labelledby"] === "add-instance-driver-label", + ); + (group!.props.onValueChange as (value: string) => void)("codex"); + tree = render(); + (findByChildren(tree, "Configure manually").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Next").props.onClick as () => void)(); + tree = render(); + (findByChildren(tree, "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "codex_work", + instance: { + driver: "codex", + enabled: true, + displayName: "Work", + config: { + setupMode: "existing", + binaryPath: "/opt/codex", + homePath: "~/.codex-work", + }, + }, + }); + }); + it("awaits an atomic create before closing and retains prepared ACP metadata", async () => { const onOpenChange = vi.fn(); let resolveMutation!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void; diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts index 6b3f22a2a73a..35bb364795fe 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts @@ -124,3 +124,8 @@ export function resolveAcpRegistryWizardNavigation( prerequisite: { step: 0, error: validation.selectionError }, }); } + +const TRAEX_BRIDGE_PROVIDER = + 'model_providers.traex={name="traex-bridge",base_url="http://127.0.0.1:8317/v1",wire_api="responses",supports_websockets=false,auth={command="sh",args=["-c","cat ~/.traex-bridge/api-key"],timeout_ms=1000}}'; + +export const TRAEX_BRIDGE_CODEX_LAUNCH_ARGS = `-c 'model_provider="traex"' -c '${TRAEX_BRIDGE_PROVIDER}'`; diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index e4febdccc649..9a39a6acdaa2 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -40,6 +40,7 @@ import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wiza import { ADD_PROVIDER_WIZARD_STEPS, ACP_REGISTRY_WIZARD_STEPS, + TRAEX_BRIDGE_CODEX_LAUNCH_ARGS, LOCAL_ACP_WIZARD_STEPS, deriveAvailableInstanceId, resolveAcpRegistryWizardNavigation, @@ -75,6 +76,7 @@ function deriveInstanceId(driver: ProviderDriverKind, label: string): string { const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/; const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); +const TRAEX_BRIDGE_PRESET = "traexBridge"; const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const DEFAULT_DRIVER_OPTION = providerClients.definitions[0]!; const EMPTY_CONFIG_DRAFT: Record = {}; @@ -113,7 +115,9 @@ export function AddProviderInstanceDialog({ const [wizardStep, setWizardStep] = useState(0); const [addingChatGptAccount, setAddingChatGptAccount] = useState(false); - const [driver, setDriver] = useState(DEFAULT_DRIVER_KIND); + const [selection, setSelection] = useState(DEFAULT_DRIVER_KIND); + const driver = + selection === TRAEX_BRIDGE_PRESET ? DEFAULT_DRIVER_KIND : ProviderDriverKind.make(selection); const [identityByDriver, setIdentityByDriver] = useState>( {}, ); @@ -139,11 +143,11 @@ export function AddProviderInstanceDialog({ const driverOption = providerClients.get(driver) ?? DEFAULT_DRIVER_OPTION; const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND; const defaultIdentity: ProviderIdentityDraft = { - label: driverOption.label, + label: selection === TRAEX_BRIDGE_PRESET ? "Traex" : driverOption.label, accentColor: "", instanceIdOverride: null, }; - const { label, accentColor, instanceIdOverride } = identityByDriver[driver] ?? defaultIdentity; + const { label, accentColor, instanceIdOverride } = identityByDriver[selection] ?? defaultIdentity; const instanceId = instanceIdOverride ?? deriveAvailableInstanceId( @@ -165,7 +169,16 @@ export function AddProviderInstanceDialog({ const identityStep = 1; const previewLabel = label.trim() || `${driverOption.label} Workspace`; - const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT; + const storedConfigDraft = configByDriver[selection] ?? EMPTY_CONFIG_DRAFT; + const defaultTraexHomePath = `~/.codex-t3/traex/${instanceId}`; + const configDraft = + selection === TRAEX_BRIDGE_PRESET + ? { + homePath: defaultTraexHomePath, + launchArgs: TRAEX_BRIDGE_CODEX_LAUNCH_ARGS, + ...storedConfigDraft, + } + : storedConfigDraft; const isLocalAcp = isAcpRegistry && isManualAcpConfiguration && configDraft.source === "local"; const localCommandPath = typeof configDraft.commandPath === "string" ? configDraft.commandPath.trim() : ""; @@ -183,14 +196,22 @@ export function AddProviderInstanceDialog({ previewLabel, null, ] as const) - : ([driverOption.label, previewLabel, null] as const); + : ([ + selection === TRAEX_BRIDGE_PRESET ? "Traex bridge" : driverOption.label, + previewLabel, + null, + ] as const); const setConfigDraft = (config: Record | undefined) => { + const overrides = { ...config }; + if (selection === TRAEX_BRIDGE_PRESET && overrides.homePath === defaultTraexHomePath) { + delete overrides.homePath; + } setConfigByDriver((existing) => { const next = { ...existing }; - if (config === undefined || Object.keys(config).length === 0) { - delete next[driver]; + if (Object.keys(overrides).length === 0) { + delete next[selection]; } else { - next[driver] = config; + next[selection] = overrides; } return next; }); @@ -198,7 +219,7 @@ export function AddProviderInstanceDialog({ const setIdentityDraft = (update: Partial) => { setIdentityByDriver((existing) => ({ ...existing, - [driver]: { ...(existing[driver] ?? defaultIdentity), ...update }, + [selection]: { ...(existing[selection] ?? defaultIdentity), ...update }, })); }; @@ -233,7 +254,7 @@ export function AddProviderInstanceDialog({ }; const handleAcpPrepared = (agent: AcpRegistrySearchAgent) => { - setDriver(ACP_REGISTRY_DRIVER_KIND); + setSelection(ACP_REGISTRY_DRIVER_KIND); const nextLabel = agent.name; const registryIconUrl = resolveOfficialAcpRegistryIconUrl(agent.icon); const nextInstanceId = deriveAvailableInstanceId( @@ -261,8 +282,15 @@ export function AddProviderInstanceDialog({ setWizardStep(1); }; + const handleTraexBridgePreset = () => { + setSelection(TRAEX_BRIDGE_PRESET); + setIsManualAcpConfiguration(false); + setHasAttemptedSubmit(false); + setWizardStep(1); + }; + const handleManualAcpConfiguration = () => { - setDriver(ACP_REGISTRY_DRIVER_KIND); + setSelection(ACP_REGISTRY_DRIVER_KIND); setSelectedAcp(null); setIsManualAcpConfiguration(true); setConfigByDriver((existing) => { @@ -280,7 +308,7 @@ export function AddProviderInstanceDialog({ }; const handleLocalAcpConfiguration = () => { - setDriver(ACP_REGISTRY_DRIVER_KIND); + setSelection(ACP_REGISTRY_DRIVER_KIND); setSelectedAcp(null); setIsManualAcpConfiguration(true); setConfigByDriver((existing) => ({ @@ -303,10 +331,7 @@ export function AddProviderInstanceDialog({ setHasAttemptedSubmit(true); if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return; - const config = - driver === "codex" - ? { ...configByDriver[driver], setupMode: "existing" } - : (configByDriver[driver] ?? {}); + const config = driver === "codex" ? { ...configDraft, setupMode: "existing" } : configDraft; const hasConfig = Object.keys(config).length > 0; const normalizedAccentColor = normalizeProviderAccentColor(accentColor); @@ -407,9 +432,9 @@ export function AddProviderInstanceDialog({ { - setDriver(ProviderDriverKind.make(value)); + setSelection(value); setIsManualAcpConfiguration(false); setHasAttemptedSubmit(false); }} @@ -452,6 +477,26 @@ export function AddProviderInstanceDialog({ {wizardStep === 0 ? (
+
+
+

Traex bridge

+

+ Run Codex against a traex-bridge container on {environmentLabel} at + 127.0.0.1:8317. Requires macOS or Linux. Uses Codex from that server's PATH + or an existing T3-managed installation. Set a custom binary path in Config. + The bridge key is read from ~/.traex-bridge/api-key on that server, not this + client. +

+
+ +
Or choose from ACP Registry @@ -662,7 +707,7 @@ export function AddProviderInstanceDialog({ > {wizardStep === 0 ? "Cancel" : "Back"} - {wizardStep === 0 && driver === "codex" ? ( + {wizardStep === 0 && selection === "codex" ? ( <>
{wizardStep === 0 ? (
-
-
-

Traex bridge

-

- Run Codex against a traex-bridge container on {environmentLabel} at - 127.0.0.1:8317. Requires macOS or Linux. Uses Codex from that server's PATH - or an existing T3-managed installation. Set a custom binary path in Config. - The bridge key is read from ~/.traex-bridge/api-key on that server, not this - client. -

-
- -
Or choose from ACP Registry diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index e12ec7909370..3f75fe883710 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -29,7 +29,7 @@ covers installation and custom configuration. Run traex-bridge on the selected environment's macOS or Linux machine at `127.0.0.1:8317`, with its API key in `~/.traex-bridge/api-key` on that machine. -In **Settings → Providers → Add provider**, choose **Use Traex**. +In **Settings → Providers → Add provider**, choose **Traex**. The preset uses Codex from that machine's PATH or an existing T3-managed installation. You can also set a custom binary path in Config. From 2c4b784d99b549304c2bbfdc9336c905ff6ea4dd Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Fri, 16 Oct 2026 23:55:52 -0700 Subject: [PATCH 004/408] fix(codex): skip self-updates for T3-managed installations Traex and other existing-mode instances can use T3-managed Codex, whose versioned package cannot run the standalone self-updater. Detect ownership through the resolved executable path and use the same maintenance policy as managed ChatGPT providers. Validated with 81 focused tests, server typecheck, targeted lint, and Gitleaks. Model: GPT-6; harness: Codex. --- .../src/provider/Drivers/CodexDriver.test.ts | 62 ++++++++++++++++--- .../src/provider/Drivers/CodexDriver.ts | 30 ++++++++- 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 697d903d2876..e24e61876783 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -183,7 +183,8 @@ it.layer(layerTest)("CodexDriver", (it) => { const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-later-install-" }); const binDir = NodePath.join(root, "bin"); yield* fs.makeDirectory(binDir); - const executablePath = NodePath.join(root, "packages", "standalone", "bin", "codex"); + const managedDirectory = NodePath.join(root, "tools", "codex"); + const executablePath = NodePath.join(managedDirectory, "0.156.1", "bin", "codex"); yield* fs.makeDirectory(NodePath.dirname(executablePath), { recursive: true }); yield* fs.writeFileString( executablePath, @@ -233,6 +234,7 @@ it.layer(layerTest)("CodexDriver", (it) => { Effect.provide(CodexAdapterV2.layerAppServerClientFactory), Effect.provideService(CodexInstallation.CodexInstallation, { ...installation, + managedDirectory, acquire: (options) => Effect.gen(function* () { expect(options).toEqual({ managedOnly: true }); @@ -272,12 +274,9 @@ it.layer(layerTest)("CodexDriver", (it) => { const snapshot = yield* instance.snapshot.refresh; expect(snapshot).toMatchObject({ installed: true, status: "ready", version: "0.156.1" }); expect(leases).toBe(0); - expect((yield* instance.snapshot.resolveMaintenance({ fresh: true })).update).toMatchObject( - { - executable: executablePath, - args: ["update"], - }, - ); + const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true }); + expect(maintenance.update).toBeNull(); + expect(yield* resolveLatestProviderVersion(maintenance)).toBeNull(); yield* Deferred.await(idle); expect(leases).toBe(0); const title = yield* instance.textGeneration.generateThreadTitle({ @@ -686,6 +685,55 @@ it.layer(layerTest)("CodexDriver", (it) => { }).pipe(Effect.scoped), ); + it.effect.each(["direct", "symlink", "path", "neighbor"] as const)( + "resolves maintenance for a %s reference to the managed installation", + (reference) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-managed-update-" }); + const managedDirectory = NodePath.join(root, "tools", "codex"); + yield* fs.makeDirectory(managedDirectory, { recursive: true }); + const binary = NodePath.join( + reference === "neighbor" ? `${managedDirectory}-external` : managedDirectory, + "0.156.1", + "bin", + "codex", + ); + yield* fs.makeDirectory(NodePath.dirname(binary), { recursive: true }); + yield* fs.writeFileString(binary, "#!/bin/sh\n", { mode: 0o755 }); + const link = NodePath.join(root, "bin", "codex"); + yield* fs.makeDirectory(NodePath.dirname(link)); + yield* fs.symlink(binary, link); + const installation = yield* CodexInstallation.CodexInstallation; + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("codex-managed-update"), + displayName: "Managed Codex", + enabled: false, + environment: [{ name: "PATH", value: NodePath.dirname(link), sensitive: false }], + config: { + ...CodexDriver.defaultConfig(), + binaryPath: reference === "path" ? "codex" : reference === "symlink" ? link : binary, + }, + }).pipe( + Effect.provideService(CodexInstallation.CodexInstallation, { + ...installation, + managedDirectory, + }), + ); + const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true }); + if (reference === "neighbor") { + expect(maintenance.update).toMatchObject({ executable: binary, args: ["update"] }); + } else { + expect(maintenance.update).toBeNull(); + expect(yield* resolveLatestProviderVersion(maintenance)).toBeNull(); + } + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), + Effect.scoped, + ), + { skip: windowsHost }, + ); + it.effect.skipIf(windowsHost)( "runs the standalone updater against the shared home, not the shadow home", () => diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 554c6d286f2c..b7e789ab7655 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -40,6 +40,7 @@ import { makePackageManagedProviderMaintenanceResolver, normalizeCommandPath, resolveProviderMaintenanceCapabilitiesEffect, + type ProviderMaintenanceCapabilitiesResolver, } from "@t3tools/provider-core/server/maintenanceResolver"; import { haveProviderSnapshotSettingsChanged, @@ -70,8 +71,11 @@ function isCodexStandaloneCommandPath(commandPath: string): boolean { * (the overlay only carries auth and a few local entries), so the updater * runs against `sharedHomePath` rather than the instance's effective home. */ -function makeCodexMaintenanceResolver(sharedHomePath: string) { - return makePackageManagedProviderMaintenanceResolver({ +function makeCodexMaintenanceResolver( + sharedHomePath: string, + managedDirectory: string, +): ProviderMaintenanceCapabilitiesResolver { + const resolver = makePackageManagedProviderMaintenanceResolver({ provider: DRIVER_KIND, npmPackageName: "@openai/codex", nativeUpdate: { @@ -80,6 +84,23 @@ function makeCodexMaintenanceResolver(sharedHomePath: string) { env: { CODEX_HOME: sharedHomePath }, }, }); + return { + resolve: (context) => + Effect.gen(function* () { + if (context) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const realManaged = yield* fs + .realPath(managedDirectory) + .pipe(Effect.orElseSucceed(() => managedDirectory)); + // T3 owns this versioned package; Codex's self-updater only handles its own installs. + if (context.realCommandPath.startsWith(`${realManaged}${path.sep}`)) { + return { provider: DRIVER_KIND, packageName: null, update: null }; + } + } + return yield* resolver.resolve(context); + }), + }; } export type CodexDriverEnv = @@ -180,7 +201,10 @@ export const CodexDriver: ProviderDriver resolveProviderMaintenanceCapabilitiesEffect( - makeCodexMaintenanceResolver(homeLayout.sharedHomePath), + makeCodexMaintenanceResolver( + homeLayout.sharedHomePath, + installation.managedDirectory, + ), { binaryPath: runtime.config.binaryPath, env: runtime.environment, From 2039e204ef13262dfacff6e96811538efefcd94d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Sat, 17 Oct 2026 00:15:26 -0700 Subject: [PATCH 005/408] fix(codex): disable unsupported agents for ChatGPT sharing Model metadata can expose collaboration tools despite multi-agent feature flags. Set agents.enabled=false for managed ChatGPT runtimes so sub-agent messages cannot produce unsupported subscription-sharing inputs. Validated with 40 focused tests, server typecheck, targeted lint, Gitleaks, and a real Codex app-server request captured by an isolated local mock endpoint. Model: GPT-6; harness: Codex. --- apps/server/src/provider/CodexManagedRuntime.test.ts | 4 +++- apps/server/src/provider/CodexManagedRuntime.ts | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/CodexManagedRuntime.test.ts b/apps/server/src/provider/CodexManagedRuntime.test.ts index 69d27f1377b6..c6a9b63156a1 100644 --- a/apps/server/src/provider/CodexManagedRuntime.test.ts +++ b/apps/server/src/provider/CodexManagedRuntime.test.ts @@ -17,7 +17,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as CodexInstallation from "./CodexInstallation.ts"; import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; -import { codexAppServerArgs } from "./codexLaunchArgs.ts"; +import { codexAppServerArgs, codexExecLaunchArgs } from "./codexLaunchArgs.ts"; import { resolveManagedCodexHomeLayout } from "./CodexManagedHome.ts"; const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -165,6 +165,8 @@ it.effect.each( assert.include(args, "features.api_key_model_discovery=true"); assert.include(args, "features.multi_agent=false"); assert.include(args, "features.multi_agent_v2=false"); + assert.include(args, "agents.enabled=false"); + assert.include(codexExecLaunchArgs(effective.config.launchArgs), "agents.enabled=false"); assert.notInclude(effective.config.launchArgs, "model_catalog_json"); assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test"); assert.include(args, "model_providers.openai_token_sharing.supports_websockets=false"); diff --git a/apps/server/src/provider/CodexManagedRuntime.ts b/apps/server/src/provider/CodexManagedRuntime.ts index 826d777f1bd7..ac8363db4f3b 100644 --- a/apps/server/src/provider/CodexManagedRuntime.ts +++ b/apps/server/src/provider/CodexManagedRuntime.ts @@ -23,6 +23,8 @@ const managedCodexLaunchArgs = [ "features.api_key_model_discovery=true", "features.multi_agent=false", "features.multi_agent_v2=false", + // Model metadata can enable collaboration despite feature flags; sharing rejects agent_message items. + "agents.enabled=false", 'model_providers.openai_token_sharing.env_key="ACCESS_TOKEN"', 'model_providers.openai_token_sharing.wire_api="responses"', "model_providers.openai_token_sharing.requires_openai_auth=false", From 047f34b82188cafb44ce6ec1169a528cf3bb1009 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Sat, 17 Oct 2026 00:50:13 -0700 Subject: [PATCH 006/408] feat(codex): add independent CLI account sign-in --- apps/server/src/provider/CodexCliAuth.test.ts | 304 ++++++++++++++++++ .../src/provider/CodexCliAuth.testkit.ts | 46 +++ apps/server/src/provider/CodexCliAuth.ts | 189 +++++++++++ apps/server/src/provider/CodexProvider.ts | 11 +- .../src/provider/Drivers/CodexDriver.test.ts | 107 ++++++ .../src/provider/Drivers/CodexDriver.ts | 168 +++++++--- .../components/onboarding/WelcomeWizard.tsx | 14 +- ...roviderInstanceDialog.environment.test.tsx | 61 +++- .../settings/AddProviderInstanceDialog.tsx | 91 ++++-- .../settings/CodexSetupSection.logic.ts | 12 +- .../ProviderAuthenticationSection.tsx | 75 ++++- .../settings/ProviderInstanceCard.tsx | 2 +- .../settings/ProviderSettingsPanel.tsx | 7 +- .../settings/ProviderSetupSection.test.tsx | 132 +++++++- .../ProviderWizardAuthenticationStep.tsx | 3 + docs/user/providers-codex.md | 23 +- packages/contracts/src/settings.ts | 2 +- .../src/server/providerAuthFlow.ts | 24 +- 18 files changed, 1168 insertions(+), 103 deletions(-) create mode 100644 apps/server/src/provider/CodexCliAuth.test.ts create mode 100644 apps/server/src/provider/CodexCliAuth.testkit.ts create mode 100644 apps/server/src/provider/CodexCliAuth.ts diff --git a/apps/server/src/provider/CodexCliAuth.test.ts b/apps/server/src/provider/CodexCliAuth.test.ts new file mode 100644 index 000000000000..c7921e6fb4d5 --- /dev/null +++ b/apps/server/src/provider/CodexCliAuth.test.ts @@ -0,0 +1,304 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; +import { CodexSettings, ProviderInstanceId, type ProviderAuthState } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { ChildProcessSpawner } from "effect/process"; + +import { codexCliEnvironment, codexCliLaunchArgs, makeCodexCliAuth } from "./CodexCliAuth.ts"; +import { materializeCodexShadowHome, resolveCodexHomeLayout } from "./Drivers/CodexHomeLayout.ts"; + +import { codexCliFixtureSource } from "./CodexCliAuth.testkit.ts"; + +const decodeCodexSettings = Schema.decodeEffect(CodexSettings); + +const makeFixture = Effect.fnUntraced(function* (mode: string, email = "one@example.test") { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-cli-auth-" }); + const sharedHome = path.join(root, "shared"); + yield* fs.makeDirectory(sharedHome); + yield* fs.writeFileString(path.join(sharedHome, "auth.json"), '{"global":"unchanged"}'); + yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "model = 'gpt-5.4'\n"); + const binaryPath = path.join(root, "codex"); + yield* fs.writeFileString(binaryPath, `#!${process.execPath}\n${codexCliFixtureSource}`, { + mode: 0o755, + }); + const spawn = yield* ChildProcessSpawner.ChildProcessSpawner; + const requests: Array<{ method: string; params?: unknown }> = []; + const children: Array = []; + const started = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const child = yield* spawn.spawn(command); + children.push(child); + return { + ...child, + stdin: child.stdin.pipe( + Sink.mapInputEffect((chunk: Uint8Array) => + Effect.gen(function* () { + const request = JSON.parse(new TextDecoder().decode(chunk)) as { + method: string; + params?: unknown; + }; + requests.push({ + method: request.method, + ...(request.params !== undefined ? { params: request.params } : {}), + }); + if (request.method === "account/login/start") + yield* Deferred.succeed(started, undefined); + return chunk; + }), + ), + ), + }; + }), + ); + const create = Effect.fnUntraced(function* (id: string, accountEmail: string) { + const homePath = path.join(root, id); + const settings = yield* decodeCodexSettings({ + setupMode: "cli", + binaryPath, + homePath: sharedHome, + shadowHomePath: homePath, + }); + yield* materializeCodexShadowHome(yield* resolveCodexHomeLayout(settings)); + const runtime = { + config: { + ...settings, + homePath, + launchArgs: codexCliLaunchArgs("-c 'model_provider=\"other\"'"), + }, + environment: codexCliEnvironment( + { + ...process.env, + T3_TEST_MODE: mode, + T3_TEST_EMAIL: accountEmail, + OPENAI_API_KEY: "must-not-reach-child", + CODEX_API_KEY: "must-not-reach-child", + ACCESS_TOKEN: "must-not-reach-child", + OPENAI_BASE_URL: "https://invalid.example.test", + T3CODE_CODEX_LAUNCH_ARGS: "--invalid-override", + }, + homePath, + ), + revision: binaryPath, + }; + const auth = yield* makeCodexCliAuth({ + instanceId: ProviderInstanceId.make(id), + homePath, + resolveRuntime: Effect.succeed(runtime), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); + const phase = (phase: ProviderAuthState["phase"]) => + auth.subscribe("owner").pipe( + Stream.filter((state) => state.phase === phase), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + return { auth, phase, homePath, runtime }; + }); + return { + ...(yield* create("one", email)), + create, + fs, + path, + sharedHome, + requests, + children, + started, + }; +}); + +it.effect.each(["early", "after-response", "missing-id"])( + "verifies native OAuth completion %s and isolates the real child environment", + (mode) => + Effect.gen(function* () { + yield* Effect.acquireRelease( + Effect.sync(() => { + for (const key of [ + "OPENAI_API_KEY", + "CODEX_API_KEY", + "OPENAI_BASE_URL", + "ACCESS_TOKEN", + "T3CODE_CODEX_LAUNCH_ARGS", + ]) { + vi.stubEnv(key, "ambient-must-not-reach-child"); + } + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const fixture = yield* makeFixture(mode); + yield* fixture.auth.start("owner"); + expect((yield* fixture.phase("succeeded")).message).toBe("Sign-in complete."); + expect( + JSON.parse( + yield* fixture.fs.readFileString(fixture.path.join(fixture.homePath, "auth.json")), + ), + ).toEqual({ + type: "chatgpt", + email: "one@example.test", + planType: "plus", + }); + const launched = JSON.parse( + yield* fixture.fs.readFileString(fixture.path.join(fixture.homePath, "launch.json")), + ); + expect(launched.params).toEqual({ type: "chatgptDeviceCode" }); + expect(launched.env).toEqual({ + CODEX_HOME: fixture.homePath, + OPENAI_API_KEY: null, + CODEX_API_KEY: null, + ACCESS_TOKEN: null, + OPENAI_BASE_URL: null, + T3CODE_CODEX_LAUNCH_ARGS: null, + }); + expect(launched.args).toEqual([ + "app-server", + "-c", + 'model_provider="other"', + "-c", + 'cli_auth_credentials_store="file"', + "-c", + 'model_provider="openai"', + "-c", + 'chatgpt_base_url="https://chatgpt.com/backend-api/"', + ]); + expect(fixture.requests.map(({ method }) => method)).toEqual([ + "initialize", + "initialized", + "account/login/start", + "account/read", + ]); + expect(yield* fixture.children[0]!.isRunning).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect.each(["failure", "no-account"])("does not accept unverified sign-in %s", (mode) => + Effect.gen(function* () { + const fixture = yield* makeFixture(mode); + yield* fixture.auth.start("owner"); + expect((yield* fixture.phase("failed")).message).toBe( + mode === "failure" + ? "Codex sign-in failed. Start again and choose the intended OpenAI account." + : "Codex could not verify the signed-in account. Try again.", + ); + expect(fixture.requests.at(-1)).toEqual({ + method: "account/login/cancel", + params: { loginId: "login-1" }, + }); + expect( + yield* fixture.fs.readFileString(fixture.path.join(fixture.sharedHome, "auth.json")), + ).toBe('{"global":"unchanged"}'); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect.each(["before-response", "waiting"])("cancels %s and closes its process", (mode) => + Effect.gen(function* () { + const fixture = yield* makeFixture(mode); + const state = yield* fixture.auth.start("owner", undefined, "browser"); + if (mode === "waiting") { + expect((yield* fixture.phase("waiting")).interaction).toEqual({ + type: "browser", + id: state.flowId, + url: "https://auth.openai.com/test", + requiresConsent: false, + }); + } else yield* Deferred.await(fixture.started); + const result = yield* fixture.auth.cancel("owner", state.flowId!); + expect(result.phase).toBe("cancelled"); + expect(yield* fixture.auth.isChangingCredentials!).toBe(false); + expect(yield* fixture.children[0]!.isRunning).toBe(false); + expect(fixture.requests.at(-1)).toEqual( + mode === "waiting" + ? { method: "account/login/cancel", params: { loginId: "login-1" } } + : { method: "account/login/start", params: { type: "chatgpt" } }, + ); + expect(yield* fixture.fs.exists(fixture.path.join(fixture.homePath, "auth.json"))).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("keeps two accounts independent and logs out only the selected overlay", () => + Effect.gen(function* () { + const fixture = yield* makeFixture("early"); + const second = yield* fixture.create("two", "two@example.test"); + yield* Effect.all([fixture.auth.start("owner"), second.auth.start("owner")], { + concurrency: 2, + }); + yield* Effect.all([fixture.phase("succeeded"), second.phase("succeeded")]); + expect(yield* fixture.fs.readLink(fixture.path.join(second.homePath, "plugins"))).toBe( + fixture.path.join(fixture.sharedHome, "plugins"), + ); + let firstSessionClosed = false; + let secondSessionClosed = false; + yield* fixture.auth.withAccess!( + Effect.addFinalizer(() => + Effect.sync(() => { + firstSessionClosed = true; + }), + ), + ); + yield* second.auth.withAccess!( + Effect.addFinalizer(() => + Effect.sync(() => { + secondSessionClosed = true; + }), + ), + ); + let stopped = false; + const result = yield* fixture.auth.logout( + Effect.sync(() => { + stopped = true; + }), + ); + expect({ phase: result.phase, message: result.message, stopped }).toEqual({ + phase: "idle", + message: "Signed out.", + stopped: true, + }); + expect({ firstSessionClosed, secondSessionClosed }).toEqual({ + firstSessionClosed: true, + secondSessionClosed: false, + }); + expect(yield* fixture.fs.exists(fixture.path.join(fixture.homePath, "auth.json"))).toBe(false); + expect( + JSON.parse(yield* fixture.fs.readFileString(fixture.path.join(second.homePath, "auth.json"))), + ).toEqual({ type: "chatgpt", email: "two@example.test", planType: "plus" }); + expect( + yield* fixture.fs.readFileString(fixture.path.join(fixture.sharedHome, "auth.json")), + ).toBe('{"global":"unchanged"}'); + expect((yield* fixture.auth.logout(Effect.void)).phase).toBe("idle"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("fails logout when Codex still reports an account", () => + Effect.gen(function* () { + const fixture = yield* makeFixture("logout-stuck"); + yield* fixture.auth.start("owner"); + yield* fixture.phase("succeeded"); + expect( + yield* fixture.auth.logout(Effect.void).pipe( + Effect.flip, + Effect.map((error) => error.detail), + ), + ).toBe("Could not sign out of Codex. Try again."); + expect((yield* fixture.phase("failed")).message).toBe("Could not sign out. Try again."); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect("releases the credential gate when Codex exits while waiting for sign-in", () => + Effect.gen(function* () { + const fixture = yield* makeFixture("exit-after-start"); + yield* fixture.auth.start("owner"); + expect((yield* fixture.phase("failed")).message).toBe( + "Codex closed before sign-in completed. Try again.", + ); + expect(yield* fixture.auth.withAccess!(Effect.succeed("available"))).toBe("available"); + expect(yield* fixture.children[0]!.isRunning).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/provider/CodexCliAuth.testkit.ts b/apps/server/src/provider/CodexCliAuth.testkit.ts new file mode 100644 index 000000000000..f7dc47a6331d --- /dev/null +++ b/apps/server/src/provider/CodexCliAuth.testkit.ts @@ -0,0 +1,46 @@ +export const codexCliFixtureSource = ` +const fs = require("node:fs"); +const path = require("node:path"); +const home = process.env.CODEX_HOME; +const mode = process.env.T3_TEST_MODE; +const authPath = path.join(home, "auth.json"); +const send = value => process.stdout.write(JSON.stringify(value) + "\\n"); +require("node:readline").createInterface({ input: process.stdin }).on("line", line => { + const { id, method, params } = JSON.parse(line); + if (id === undefined) return; + const reply = result => send({ id, result }); + if (method === "initialize") return reply({ userAgent: "codex/0.156.1", codexHome: home, platformFamily: "unix", platformOs: "macos" }); + if (method === "account/login/start") { + fs.writeFileSync(path.join(home, "launch.json"), JSON.stringify({ params, args: process.argv.slice(2), env: { + CODEX_HOME: home, + OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? null, + CODEX_API_KEY: process.env.CODEX_API_KEY ?? null, + ACCESS_TOKEN: process.env.ACCESS_TOKEN ?? null, + OPENAI_BASE_URL: process.env.OPENAI_BASE_URL ?? null, + T3CODE_CODEX_LAUNCH_ARGS: process.env.T3CODE_CODEX_LAUNCH_ARGS ?? null, + }})); + if (mode === "before-response") return; + const complete = () => { + if (mode !== "no-account" && mode !== "failure") fs.writeFileSync(authPath, JSON.stringify({ type: "chatgpt", email: process.env.T3_TEST_EMAIL, planType: "plus" })); + send({ method: "account/login/completed", params: { + loginId: mode === "missing-id" ? null : "login-1", + success: mode !== "failure", error: mode === "failure" ? "SECRET_NATIVE_FAILURE" : null, + }}); + }; + if (mode !== "waiting" && mode !== "after-response" && mode !== "exit-after-start") complete(); + reply(params.type === "chatgpt" ? { type: "chatgpt", loginId: "login-1", authUrl: "https://auth.openai.com/test" } : { type: "chatgptDeviceCode", loginId: "login-1", verificationUrl: "https://auth.openai.com/device", userCode: "TEST-CODE" }); + if (mode === "after-response") setImmediate(complete); + if (mode === "exit-after-start") setImmediate(() => process.exit(1)); + return; + } + if (method === "account/read") return reply({ account: fs.existsSync(authPath) ? JSON.parse(fs.readFileSync(authPath, "utf8")) : null, requiresOpenaiAuth: true }); + if (method === "account/login/cancel") { + send({ method: "account/login/completed", params: { loginId: "login-1", success: true } }); + return reply({ status: "canceled" }); + } + if (method === "account/logout") { + if (mode !== "logout-stuck") fs.rmSync(authPath, { force: true }); + return reply({}); + } +}); +`; diff --git a/apps/server/src/provider/CodexCliAuth.ts b/apps/server/src/provider/CodexCliAuth.ts new file mode 100644 index 000000000000..e3d46c46ec1b --- /dev/null +++ b/apps/server/src/provider/CodexCliAuth.ts @@ -0,0 +1,189 @@ +import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts"; +import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Scope from "effect/Scope"; +import * as Schema from "effect/Schema"; +import { ChildProcessSpawner } from "effect/process"; +import type * as CodexSchema from "effect-codex-app-server/schema"; + +import type { CodexEffectiveRuntime } from "./CodexManagedRuntime.ts"; +import { withCodexAppServerClient } from "./CodexProvider.ts"; + +const isProviderSetupError = Schema.is(ProviderSetupError); + +export const codexCliLaunchArgs = (launchArgs: string) => + [ + launchArgs, + ...[ + 'cli_auth_credentials_store="file"', + 'model_provider="openai"', + 'chatgpt_base_url="https://chatgpt.com/backend-api/"', + ].map((value) => `-c '${value}'`), + ].join(" "); + +export function codexCliEnvironment(environment: NodeJS.ProcessEnv, homePath: string) { + const next: NodeJS.ProcessEnv = { ...environment, CODEX_HOME: homePath }; + for (const key of [ + "OPENAI_API_KEY", + "CODEX_API_KEY", + "OPENAI_BASE_URL", + "ACCESS_TOKEN", + "T3CODE_CODEX_LAUNCH_ARGS", + ]) { + delete next[key]; + } + return next; +} + +export const makeCodexCliAuth = Effect.fn("makeCodexCliAuth")(function* (options: { + readonly instanceId: ProviderInstanceId; + readonly homePath: string; + readonly resolveRuntime: Effect.Effect; +}) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const open = options.resolveRuntime.pipe( + Effect.flatMap((runtime) => + withCodexAppServerClient({ + binaryPath: runtime.config.binaryPath, + homePath: runtime.config.homePath, + launchArgs: runtime.config.launchArgs, + environment: runtime.environment, + extendEnv: false, + cwd: options.homePath, + }), + ), + ); + return yield* ProviderAuthFlow.make({ + instanceId: options.instanceId, + credentialBinding: { owner: "provider", key: options.homePath }, + defaultMethodId: "deviceCode", + methods: Effect.succeed([ + { + id: "deviceCode", + name: "Device code", + description: "Sign in from any browser, including on another device.", + type: "agent", + }, + { + id: "browser", + name: "Browser on server machine", + description: "Use a browser on the machine running this environment.", + type: "agent", + }, + ]), + authenticate: (methodId, context) => + Effect.gen(function* () { + const { client, exitCode } = yield* open; + const completions = + yield* Queue.unbounded(); + yield* client.handleServerNotification("account/login/completed", (notification) => + Queue.offer(completions, notification).pipe(Effect.asVoid), + ); + const login = yield* client.request("account/login/start", { + type: methodId === "browser" ? "chatgpt" : "chatgptDeviceCode", + }); + if (login.type !== "chatgpt" && login.type !== "chatgptDeviceCode") { + return yield* new ProviderSetupError({ + instanceId: options.instanceId, + operation: "start", + detail: "Codex did not start the requested sign-in method. Try again.", + }); + } + let verified = false; + yield* Effect.addFinalizer(() => + verified + ? Effect.void + : client + .request("account/login/cancel", { loginId: login.loginId }) + .pipe(Effect.timeout("2 seconds"), Effect.ignore), + ); + yield* context.setInteraction( + login.type === "chatgpt" + ? { + type: "browser", + id: context.flowId, + url: login.authUrl, + requiresConsent: false, + } + : { + type: "deviceCode", + id: context.flowId, + url: login.verificationUrl, + userCode: login.userCode, + }, + ); + const completion = yield* Effect.raceFirst( + Effect.gen(function* () { + let notification = yield* Queue.take(completions); + while (notification.loginId != null && notification.loginId !== login.loginId) { + notification = yield* Queue.take(completions); + } + return notification; + }), + exitCode.pipe( + Effect.flatMap( + () => + new ProviderSetupError({ + instanceId: options.instanceId, + operation: "start", + detail: "Codex closed before sign-in completed. Try again.", + }), + ), + ), + ); + if (!completion.success) { + return yield* new ProviderSetupError({ + instanceId: options.instanceId, + operation: "start", + detail: "Codex sign-in failed. Start again and choose the intended OpenAI account.", + }); + } + yield* context.verifying; + const account = yield* client.request("account/read", {}); + if (account.account?.type !== "chatgpt") { + return yield* new ProviderSetupError({ + instanceId: options.instanceId, + operation: "start", + detail: "Codex could not verify the signed-in account. Try again.", + }); + } + verified = true; + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.mapError((cause) => + isProviderSetupError(cause) + ? cause + : new ProviderSetupError({ + instanceId: options.instanceId, + operation: "start", + detail: "Could not complete Codex sign-in. Try again.", + }), + ), + ), + logout: Effect.gen(function* () { + const { client } = yield* open; + yield* client.request("account/logout", undefined); + const account = yield* client.request("account/read", {}); + if (account.account) { + return yield* new ProviderSetupError({ + instanceId: options.instanceId, + operation: "logout", + detail: "Codex is still signed in. Try signing out again.", + }); + } + }).pipe( + Effect.scoped, + Effect.timeout("20 seconds"), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.mapError( + () => + new ProviderSetupError({ + instanceId: options.instanceId, + operation: "logout", + detail: "Could not sign out of Codex. Try again.", + }), + ), + ), + }); +}); diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index f4f123dc1a25..a4c80bdeb108 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -410,6 +410,7 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu readonly launchArgs?: string | undefined; readonly cwd: string; readonly environment?: NodeJS.ProcessEnv | undefined; + readonly extendEnv?: boolean; }) { // `~` is not shell-expanded when env vars are set via `child_process.spawn`, // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip @@ -425,14 +426,14 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu const spawnCommand = yield* resolveSpawnCommand( input.binaryPath, codexAppServerArgs(input.launchArgs), - { env: environment, extendEnv: true }, + { env: environment, extendEnv: input.extendEnv ?? true }, ); const child = yield* spawner .spawn( ChildProcess.make(spawnCommand.command, spawnCommand.args, { cwd: input.cwd, env: environment, - extendEnv: true, + extendEnv: input.extendEnv ?? true, forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER, shell: spawnCommand.shell, }), @@ -452,7 +453,7 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu ); const initialize = yield* client.request("initialize", buildCodexInitializeParams()); yield* client.notify("initialized", undefined); - return { client, initialize }; + return { client, initialize, exitCode: child.exitCode }; }); const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { @@ -462,6 +463,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun readonly cwd: string; readonly customModels?: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; + readonly extendEnv?: boolean; readonly skipNativeUsage?: boolean; }) { const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now); @@ -530,6 +532,7 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi readonly launchArgs?: string; readonly cwd: string; readonly environment?: NodeJS.ProcessEnv; + readonly extendEnv?: boolean; }) { const { client } = yield* withCodexAppServerClient(input); const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] }); @@ -620,6 +623,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu readonly cwd: string; readonly customModels: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; + readonly extendEnv?: boolean; readonly skipNativeUsage?: boolean; }) => Effect.Effect< CodexAppServerProviderSnapshot, @@ -661,6 +665,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu cwd: process.cwd(), customModels: codexSettings.customModels, environment: resolvedEnvironment, + ...(codexSettings.setupMode === "cli" ? { extendEnv: false } : {}), ...(managedAuth ? { skipNativeUsage: true } : {}), }).pipe( Effect.scoped, diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index e24e61876783..d53f83f4a720 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -35,6 +35,7 @@ import { resolveLatestProviderVersion, } from "@t3tools/provider-core/server/maintenanceResolver"; import { CodexDriver } from "./CodexDriver.ts"; +import { codexCliFixtureSource } from "../CodexCliAuth.testkit.ts"; import * as CodexAdapterV2 from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -96,6 +97,112 @@ const noSpawn = ChildProcessSpawner.make(() => const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); it.layer(layerTest)("CodexDriver", (it) => { + it.effect.skipIf(windowsHost)( + "guards native account consumers and refreshes after cancellation", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-cli-driver-" }); + const binaryPath = NodePath.join(root, "codex"); + const sharedHome = NodePath.join(root, "shared"); + const ignoredShadow = NodePath.join(root, "user-shadow"); + const instanceId = ProviderInstanceId.make("codex-cli-driver"); + const ownedHome = NodePath.join(config.stateDir, "providers", "codex", instanceId, "cli"); + const source = codexCliFixtureSource + .replace( + 'if (method === "account/login/start") {', + 'if (method === "account/login/start") { fs.writeFileSync(path.join(home, "login-started"), "yes");', + ) + .replace( + 'if (method === "account/read") return', + 'if (method === "account/read" && !fs.existsSync(path.join(home, "login-started"))) return; if (method === "account/read") return', + ); + yield* fs.writeFileString(binaryPath, `#!${process.execPath}\n${source}`, { mode: 0o755 }); + const firstSpawn = yield* Deferred.make(); + const children: Array = []; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const instance = yield* CodexDriver.create({ + instanceId, + displayName: "Native account", + enabled: true, + environment: [{ name: "T3_TEST_MODE", value: "waiting", sensitive: false }], + config: { + ...CodexDriver.defaultConfig(), + setupMode: "cli", + binaryPath, + homePath: sharedHome, + shadowHomePath: ignoredShadow, + }, + }).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const child = yield* spawner.spawn(command); + children.push(child); + yield* Deferred.succeed(firstSpawn, undefined); + return child; + }), + ), + ), + ); + expect(instance.auth?.credentialBinding).toEqual({ owner: "provider", key: ownedHome }); + const checking = yield* instance.snapshot.refresh.pipe(Effect.forkScoped); + yield* Deferred.await(firstSpawn); + yield* instance.auth!.start("owner"); + const waiting = yield* instance.auth!.subscribe("owner").pipe( + Stream.filter((state) => state.phase === "waiting"), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect((yield* Fiber.join(checking)).auth.status).toBe("unknown"); + expect(yield* children[0]!.isRunning).toBe(false); + const beforeBlockedCalls = children.length; + expect((yield* instance.snapshot.refresh).auth.status).toBe("unknown"); + expect( + yield* instance.snapshotForCwd!(root).pipe( + Effect.flip, + Effect.map((error) => error._tag), + ), + ).toBe("ProviderDriverError"); + expect( + yield* instance.consumeResetCredit!().pipe( + Effect.flip, + Effect.map((error) => error._tag), + ), + ).toBe("ProviderDriverError"); + expect( + yield* instance.textGeneration + .generateThreadTitle({ + cwd: root, + message: "Title", + modelSelection: { instanceId, model: "gpt-5.4" }, + }) + .pipe( + Effect.flip, + Effect.map((error) => error._tag), + ), + ).toBe("TextGenerationError"); + expect(children.length).toBe(beforeBlockedCalls); + const automaticRefresh = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((value) => value.installed && value.auth.status === "unauthenticated"), + Stream.runHead, + Effect.map(Option.getOrThrow), + Effect.forkScoped, + ); + yield* instance.auth!.cancel("owner", waiting.flowId!); + const refreshed = yield* Fiber.join(automaticRefresh); + expect(refreshed).toMatchObject({ + installed: true, + auth: { status: "unauthenticated" }, + setup: { canAuthenticate: true }, + runtimePaths: { homePath: sharedHome, shadowHomePath: ownedHome }, + }); + expect(yield* fs.exists(ignoredShadow)).toBe(false); + }).pipe(Effect.scoped), + ); + it.effect.each([true, false])( "keeps the instance PATH boundary when host Codex exists and managed installation is %s", (managedInstalled) => diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index b7e789ab7655..a0657494cecb 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -1,10 +1,12 @@ -import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts"; +import { CodexSettings, ProviderDriverKind, TextGenerationError } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import { resolveCommandPath } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { codexCliEnvironment, codexCliLaunchArgs, makeCodexCliAuth } from "../CodexCliAuth.ts"; import type { CodexEffectiveRuntime } from "../CodexManagedRuntime.ts"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; @@ -148,11 +150,29 @@ export const CodexDriver: ProviderDriver(task: Effect.Effect) => + auth?.withAccess ? auth.withAccess(task) : task; + const stampSnapshot = (draft: Parameters[0]) => + stampIdentity({ + ...draft, + ...(cliAccount + ? { + setup: { ...draft.setup, canAuthenticate: true, canInstall: true }, + ...(draft.auth.status === "unauthenticated" + ? { message: "Sign in with Codex CLI in provider settings." } + : {}), + runtimePaths: { + homePath: homeLayout.sharedHomePath, + shadowHomePath: accountKey, + }, + } + : {}), + }); const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( resolveRuntime.pipe( Effect.flatMap((runtime) => @@ -225,7 +267,7 @@ export const CodexDriver: ProviderDriver snapshot.applyUsageLimits(update), resolveRuntime }, ).pipe( @@ -245,14 +287,20 @@ export const CodexDriver: ProviderDriver - checkCodexProviderStatus(runtime.config, undefined, runtime.environment), + withAccess( + resolveRuntime.pipe( + Effect.flatMap((runtime) => + checkCodexProviderStatus(runtime.config, undefined, runtime.environment), + ), ), + ).pipe( Effect.scoped, + Effect.catchTags({ + ProviderSetupError: () => makePendingCodexProvider(effectiveConfig), + }), ), currentCatalog, - (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), + (draft, catalog) => stampSnapshot(applyCodexModelCatalog(draft, catalog)), { concurrent: true }, ), ), @@ -270,7 +318,7 @@ export const CodexDriver: ProviderDriver stampIdentity(applyCodexModelCatalog(draft, catalog)), + (draft, catalog) => stampSnapshot(applyCodexModelCatalog(draft, catalog)), ), checkProvider, enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => @@ -295,30 +343,70 @@ export const CodexDriver: ProviderDriver + ["succeeded", "failed", "cancelled"].includes(state.phase) || + (state.phase === "idle" && state.message !== null), + ), + Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause)), + Effect.forkScoped, + ); + } + const nativeGeneration = yield* makeCodexTextGeneration( effectiveConfig, processEnv, snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), resolveRuntime, ); + const protect = (operation: string, task: Effect.Effect) => + withAccess(task).pipe( + Effect.scoped, + Effect.mapError( + (cause) => + new TextGenerationError({ + operation, + detail: cause.detail, + }), + ), + ); + const textGeneration: ProviderInstance["textGeneration"] = auth + ? { + generateCommitMessage: (input) => + protect("generateCommitMessage", nativeGeneration.generateCommitMessage(input)), + generatePrContent: (input) => + protect("generatePrContent", nativeGeneration.generatePrContent(input)), + generateBranchName: (input) => + protect("generateBranchName", nativeGeneration.generateBranchName(input)), + generateThreadTitle: (input) => + protect("generateThreadTitle", nativeGeneration.generateThreadTitle(input)), + generateReviewGuide: (input) => + protect("generateReviewGuide", nativeGeneration.generateReviewGuide(input)), + } + : nativeGeneration; const snapshotForCwd = (cwd: string) => !effectiveConfig.enabled ? snapshot.getSnapshot : Effect.all([ snapshot.getSnapshot, - resolveRuntime.pipe( - Effect.flatMap((runtime) => - probeCodexSkillsForCwd({ - binaryPath: runtime.config.binaryPath, - homePath: runtime.config.homePath, - launchArgs: resolveCodexLaunchArgs( - runtime.config.launchArgs, - runtime.environment, - ), - cwd, - environment: runtime.environment, - }), + withAccess( + resolveRuntime.pipe( + Effect.flatMap((runtime) => + probeCodexSkillsForCwd({ + binaryPath: runtime.config.binaryPath, + homePath: runtime.config.homePath, + launchArgs: resolveCodexLaunchArgs( + runtime.config.launchArgs, + runtime.environment, + ), + cwd, + environment: runtime.environment, + ...(cliAccount ? { extendEnv: false } : {}), + }), + ), ), + ).pipe( Effect.scoped, Effect.timeout("20 seconds"), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -343,24 +431,29 @@ export const CodexDriver: ProviderDriver = () => resetCreditCoordinator .redeem(accountKey, (idempotencyKey) => - Effect.gen(function* () { - const runtime = yield* resolveRuntime; - const { client } = yield* withCodexAppServerClient({ - binaryPath: runtime.config.binaryPath, - homePath: runtime.config.homePath, - launchArgs: resolveCodexLaunchArgs(runtime.config.launchArgs, runtime.environment), - cwd: process.cwd(), - environment: runtime.environment, - }); - const response = yield* client.request("account/rateLimitResetCredit/consume", { - idempotencyKey, - }); - return response.outcome; - }).pipe(Effect.scoped, Effect.timeout("20 seconds")), + withAccess( + Effect.gen(function* () { + const runtime = yield* resolveRuntime; + const { client } = yield* withCodexAppServerClient({ + binaryPath: runtime.config.binaryPath, + homePath: runtime.config.homePath, + launchArgs: resolveCodexLaunchArgs( + runtime.config.launchArgs, + runtime.environment, + ), + cwd: process.cwd(), + environment: runtime.environment, + ...(cliAccount ? { extendEnv: false } : {}), + }); + const response = yield* client.request("account/rateLimitResetCredit/consume", { + idempotencyKey, + }); + return response.outcome; + }), + ).pipe(Effect.scoped, Effect.timeout("20 seconds")), ) .pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -411,6 +504,7 @@ export const CodexDriver: ProviderDriver + ) : existingChosen || mode === "cli" ? ( diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx index 6bcd88984641..b744b59bf0d9 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx @@ -136,7 +136,7 @@ function button(dialog: unknown, label: string) { function prepareInstance() { let dialog = renderDialog(); - (button(dialog, "Configure manually").props.onClick as () => void)(); + (button(dialog, "Use existing Codex CLI").props.onClick as () => void)(); dialog = renderDialog(); const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work"); if (!label) throw new Error("Missing instance label input."); @@ -187,7 +187,7 @@ describe("AddProviderInstanceDialog environment routing", () => { }, }); let tree = render(); - (findByChildren(tree, "Configure manually").props.onClick as () => void)(); + (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); tree = render(); (findByChildren(tree, "Next").props.onClick as () => void)(); tree = render(); @@ -212,6 +212,59 @@ describe("AddProviderInstanceDialog environment routing", () => { expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId); }); + it("creates a native Codex account without runtime overrides and continues to sign-in", async () => { + (button(renderDialog(), "Sign in with Codex CLI").props.onClick as () => void)(); + let tree = renderDialog(); + const label = visitElements(tree, (entry) => entry.props.placeholder === "e.g. Work")!; + (label.props.onChange as (event: { target: { value: string } }) => void)({ + target: { value: "Personal" }, + }); + tree = renderDialog(); + (button(tree, "Continue to sign-in").props.onClick as () => void)(); + await Promise.resolve(); + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "codex_personal", + instance: { + driver: "codex", + enabled: true, + displayName: "Personal", + config: { setupMode: "cli" }, + }, + }); + const authentication = visitElements( + renderDialog(), + (entry) => + typeof entry.type === "function" && entry.type.name === "ProviderWizardAuthenticationStep", + ); + expect(authentication?.props).toMatchObject({ + environmentId: remoteEnvironmentId, + instanceId: "codex_personal", + autoOpenBrowser: true, + }); + expect(actions.onOpenChange).not.toHaveBeenCalled(); + }); + + it("preserves the existing CLI configuration after leaving the native account path", async () => { + (button(renderDialog(), "Sign in with Codex CLI").props.onClick as () => void)(); + (button(renderDialog(), "Back").props.onClick as () => void)(); + (button(renderDialog(), "Use existing Codex CLI").props.onClick as () => void)(); + (button(renderDialog(), "Next").props.onClick as () => void)(); + (button(renderDialog(), "Add instance").props.onClick as () => void)(); + await Promise.resolve(); + expect(settingsHooks.mutate).toHaveBeenCalledWith({ + operation: "create", + instanceId: "codex_2", + instance: { + driver: "codex", + enabled: true, + displayName: "Codex", + config: { setupMode: "existing" }, + }, + }); + expect(actions.onOpenChange).toHaveBeenCalledWith(false); + }); + it("persists a Traex preset as an isolated Codex instance in the selected environment", async () => { settingsHooks.read.mockReturnValue({ providerInstances: { codex_traex: { driver: "codex", enabled: true } }, @@ -419,7 +472,7 @@ describe("AddProviderInstanceDialog environment routing", () => { it("restores the manual Codex draft after choosing Traex and switching back", async () => { let tree = render(); - (findByChildren(tree, "Configure manually").props.onClick as () => void)(); + (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); tree = render(); const label = visitElements(tree, (element) => element.props.id === "add-provider-label"); (label!.props.onChange as (event: { target: { value: string } }) => void)({ @@ -449,7 +502,7 @@ describe("AddProviderInstanceDialog environment routing", () => { ); (group!.props.onValueChange as (value: string) => void)("codex"); tree = render(); - (findByChildren(tree, "Configure manually").props.onClick as () => void)(); + (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); tree = render(); (findByChildren(tree, "Next").props.onClick as () => void)(); tree = render(); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index c0cb747db4b9..dd53057181f9 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -120,7 +120,7 @@ export function AddProviderInstanceDialog({ const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); const [wizardStep, setWizardStep] = useState(0); - const [addingChatGptAccount, setAddingChatGptAccount] = useState(false); + const [codexSetupMode, setCodexSetupMode] = useState<"cli" | "existing" | "managed" | null>(null); const [selection, setSelection] = useState(DEFAULT_DRIVER_KIND); const driver = selection === TRAEX_BRIDGE_PRESET ? DEFAULT_DRIVER_KIND : ProviderDriverKind.make(selection); @@ -148,6 +148,7 @@ export function AddProviderInstanceDialog({ const driverOption = providerClients.get(driver) ?? DEFAULT_DRIVER_OPTION; const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND; + const isCliAccount = selection === "codex" && codexSetupMode === "cli"; const defaultIdentity: ProviderIdentityDraft = { label: selection === TRAEX_BRIDGE_PRESET ? "Traex" : driverOption.label, accentColor: "", @@ -234,7 +235,11 @@ export function AddProviderInstanceDialog({ if (navigation.kind === "blocked") { setHasAttemptedSubmit(true); } - if (isAcpRegistry && !isLocalAcp && navigation.kind === "navigate" && navigation.step === 2) { + if ( + ((isAcpRegistry && !isLocalAcp) || isCliAccount) && + navigation.kind === "navigate" && + navigation.step === 2 + ) { void handleSave(); return; } @@ -330,7 +335,11 @@ export function AddProviderInstanceDialog({ setHasAttemptedSubmit(true); if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return; - const config = driver === "codex" ? { ...configDraft, setupMode: "existing" } : configDraft; + const config = isCliAccount + ? { setupMode: "cli" } + : driver === "codex" + ? { ...configDraft, setupMode: "existing" } + : configDraft; const hasConfig = Object.keys(config).length > 0; const normalizedAccentColor = normalizeProviderAccentColor(accentColor); @@ -360,7 +369,7 @@ export function AddProviderInstanceDialog({ return; } onCreated?.(brandedId); - if (isAcpRegistry && !isLocalAcp) { + if ((isAcpRegistry && !isLocalAcp) || isCliAccount) { setCreatedInstanceId(brandedId); setIsSaving(false); setWizardStep(2); @@ -374,7 +383,7 @@ export function AddProviderInstanceDialog({ onOpenChange(false); }; - if (addingChatGptAccount) { + if (codexSetupMode === "managed") { return ( )} @@ -417,6 +427,7 @@ export function AddProviderInstanceDialog({ environmentId={environmentId} environmentLabel={environmentLabel} instanceId={createdInstanceId} + autoOpenBrowser={isCliAccount} onFinish={() => onOpenChange(false)} /> ) : ( @@ -434,6 +445,7 @@ export function AddProviderInstanceDialog({ value={selection} onValueChange={(value) => { setSelection(value); + setCodexSetupMode(null); setIsManualAcpConfiguration(false); setHasAttemptedSubmit(false); }} @@ -472,6 +484,54 @@ export function AddProviderInstanceDialog({
+ {wizardStep === 0 && selection === "codex" ? ( +
+
+ +

+ Add an independent Codex account. Keep your shared skills, plugins, and thread + history. +

+
+
+ +

+ Use the CLI account and runtime already configured on {environmentLabel}. +

+
+
+ setCodexSetupMode("managed")} + > + Use ChatGPT sharing + +

+ Connect through ChatGPT subscription sharing. Some native Codex features are + unavailable. +

+
+
+ ) : null} + {wizardStep === 0 ? (
@@ -650,7 +710,7 @@ export function AddProviderInstanceDialog({ /> - {!isAcpRegistry && driverSettingsFields.length > 0 ? ( + {!isAcpRegistry && !isCliAccount && driverSettingsFields.length > 0 ? ( - ) : !isAcpRegistry && wizardStep === 2 ? ( + ) : !isAcpRegistry && !isCliAccount && wizardStep === 2 ? (

This driver has no required configuration. You can add the instance now. @@ -684,17 +744,8 @@ export function AddProviderInstanceDialog({ > {wizardStep === 0 ? "Cancel" : "Back"} - {wizardStep === 0 && selection === "codex" ? ( - <> - - setAddingChatGptAccount(true)} - /> - - ) : wizardStep < (isAcpRegistry ? 1 : 2) ? ( + {wizardStep === 0 && selection === "codex" ? null : wizardStep < + (isAcpRegistry || isCliAccount ? 1 : 2) ? ( diff --git a/apps/web/src/components/settings/CodexSetupSection.logic.ts b/apps/web/src/components/settings/CodexSetupSection.logic.ts index 46868d513db0..9fa9d11fcd13 100644 --- a/apps/web/src/components/settings/CodexSetupSection.logic.ts +++ b/apps/web/src/components/settings/CodexSetupSection.logic.ts @@ -1,8 +1,6 @@ -export function readCodexSetupMode(config: unknown): "managed" | "existing" { - return config !== null && - typeof config === "object" && - "setupMode" in config && - config.setupMode === "managed" - ? "managed" - : "existing"; +export function readCodexSetupMode(config: unknown): "managed" | "existing" | "cli" { + if (config !== null && typeof config === "object" && "setupMode" in config) { + if (config.setupMode === "managed" || config.setupMode === "cli") return config.setupMode; + } + return "existing"; } diff --git a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx index 9e3037c79a48..6ce68c90bd33 100644 --- a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx +++ b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx @@ -10,7 +10,7 @@ import type { ProviderInstanceId, ServerProvider, } from "@t3tools/contracts"; -import { lazy, Suspense, useRef, useState } from "react"; +import { lazy, Suspense, useEffect, useRef, useState } from "react"; import { CopyIcon } from "lucide-react"; import { writeTextToClipboard } from "../../hooks/useCopyToClipboard"; @@ -33,12 +33,14 @@ export function ProviderAuthenticationSection({ instanceId, provider, readOnly, + autoOpenBrowser = false, }: { readonly environmentId: EnvironmentId; readonly environmentLabel: string; readonly instanceId: ProviderInstanceId; readonly provider: ServerProvider; readonly readOnly: boolean; + readonly autoOpenBrowser?: boolean; }) { const target = { environmentId, input: { instanceId } }; const query = useEnvironmentQuery(serverEnvironment.providerAuthState(target)); @@ -53,6 +55,9 @@ export function ProviderAuthenticationSection({ const [error, setError] = useState(null); const [pending, setPending] = useState(false); const pendingRef = useRef(false); + const reservedBrowser = useRef(null); + const [browserFlowId, setBrowserFlowId] = useState(null); + const handledBrowserFlow = useRef(null); const terminalQueue = useRef([]); const terminalSending = useRef(false); const auth = query.data; @@ -99,6 +104,60 @@ export function ProviderAuthenticationSection({ ? interaction.url : auth?.authorizationUrl; + useEffect(() => () => reservedBrowser.current?.close(), []); + useEffect(() => { + if (!browserFlowId || handledBrowserFlow.current === browserFlowId) return; + if (query.error || (auth?.flowId === browserFlowId && !active)) { + reservedBrowser.current?.close(); + reservedBrowser.current = null; + handledBrowserFlow.current = browserFlowId; + return; + } + if (auth?.flowId !== browserFlowId || !url || !interaction) return; + if ( + interaction.type !== "deviceCode" && + (interaction.type !== "browser" || interaction.requiresConsent) + ) + return; + const tab = reservedBrowser.current; + reservedBrowser.current = null; + handledBrowserFlow.current = browserFlowId; + if (tab && !tab.closed) { + tab.location.href = url; + } else { + void ensureLocalApi() + .shell.openExternal(url) + .catch(() => { + setError("Could not open the sign-in page. Use Open browser or copy the link."); + }); + } + }, [active, auth?.flowId, browserFlowId, interaction, query.error, url]); + + async function beginSignIn() { + if (pendingRef.current) return; + if (autoOpenBrowser && !window.desktopBridge) { + reservedBrowser.current = window.open("", "_blank"); + if (reservedBrowser.current) reservedBrowser.current.opener = null; + } + const succeeded = await run(async () => { + const result = await start({ + environmentId, + input: { + instanceId, + ...(methodId && auth?.methods?.some((method) => method.id === methodId) + ? { methodId } + : {}), + }, + }); + if (autoOpenBrowser && result._tag === "Success") setBrowserFlowId(result.value.flowId); + return result; + }); + if (!succeeded) { + reservedBrowser.current?.close(); + reservedBrowser.current = null; + } + } + async function run(command: () => Promise>) { if (pendingRef.current) return false; pendingRef.current = true; @@ -275,19 +334,7 @@ export function ProviderAuthenticationSection({ size="sm" variant="outline" disabled={disabled || !provider.enabled || !provider.installed || !auth} - onClick={() => - void run(() => - start({ - environmentId, - input: { - instanceId, - ...(methodId && auth?.methods?.some((method) => method.id === methodId) - ? { methodId } - : {}), - }, - }), - ) - } + onClick={() => void beginSignIn()} > {signedIn ? "Change account" diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index d56a2b95aa7e..e4b6a9178b23 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -1202,7 +1202,7 @@ export function ProviderInstanceCard({ ) : null} - {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? ( + {instance.driver === "codex" && readCodexSetupMode(instance.config) !== "existing" ? (

@@ -1010,6 +1010,9 @@ export function EnvironmentProviderSettings({ instanceId={row.instanceId} provider={liveProvider} readOnly={readOnly} + autoOpenBrowser={ + row.driver === "codex" && readCodexSetupMode(row.instance.config) === "cli" + } /> ) : mode === "editor" && !readOnly && diff --git a/apps/web/src/components/settings/ProviderSetupSection.test.tsx b/apps/web/src/components/settings/ProviderSetupSection.test.tsx index 214546c48f70..9e52e94a7462 100644 --- a/apps/web/src/components/settings/ProviderSetupSection.test.tsx +++ b/apps/web/src/components/settings/ProviderSetupSection.test.tsx @@ -26,6 +26,8 @@ const setup = vi.hoisted(() => ({ cancelInstall: vi.fn(), removeInstall: vi.fn(), confirm: vi.fn(), + openExternal: vi.fn(), + effects: [] as Array<() => void | (() => void)>, })); vi.mock("react", async (importOriginal) => { @@ -34,6 +36,9 @@ vi.mock("react", async (importOriginal) => { return { ...actual, useRef: reactHookHarness.useRef, + useEffect: (effect: () => void | (() => void)) => { + setup.effects.push(effect); + }, useState: reactHookHarness.useState, }; }); @@ -72,7 +77,10 @@ vi.mock("../../state/query", () => ({ })); vi.mock("../../localApi", () => ({ - ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }), + ensureLocalApi: () => ({ + dialogs: { confirm: setup.confirm }, + shell: { openExternal: setup.openExternal }, + }), })); import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection"; @@ -209,6 +217,7 @@ async function flushPromises() { describe("Antigravity setup", () => { beforeEach(() => { hooks.reset(); + setup.effects = []; vi.clearAllMocks(); setup.auth = authState(); setup.installation = { @@ -424,3 +433,124 @@ describe("Antigravity setup", () => { }, ); }); + +const nativeInstanceId = ProviderInstanceId.make("codex_personal"); +function renderNativeAuth(autoOpenBrowser = true) { + hooks.beginRender(); + const view = ProviderAuthenticationSection({ + environmentId, + environmentLabel: "Remote device", + instanceId: nativeInstanceId, + provider: { + ...provider, + instanceId: nativeInstanceId, + driver: ProviderDriverKind.make("codex"), + }, + readOnly: false, + autoOpenBrowser, + }); + for (const effect of setup.effects.splice(0)) effect(); + return view; +} + +describe("Native Codex sign-in browser", () => { + beforeEach(() => { + hooks.reset(); + setup.effects = []; + vi.clearAllMocks(); + setup.auth = authState({ + instanceId: nativeInstanceId, + phase: "idle", + flowId: null, + authorizationUrl: null, + }); + setup.startAuth.mockResolvedValue({ + _tag: "Success", + value: { ...setup.auth, phase: "starting", flowId: "native-flow" }, + }); + setup.openExternal.mockResolvedValue(undefined); + }); + + it("opens the initiating flow's page and leaves a passive subscription alone", async () => { + const tab = { location: { href: "" }, opener: {}, close: vi.fn(), closed: false }; + const open = vi.fn(() => tab); + vi.stubGlobal("window", { open }); + try { + click(renderNativeAuth(), "Sign in"); + expect(open).toHaveBeenCalledWith("", "_blank"); + await flushPromises(); + setup.auth = authState({ + instanceId: nativeInstanceId, + phase: "waiting", + flowId: "native-flow", + interaction: { + type: "deviceCode", + id: "native-flow", + url: "https://auth.openai.com/device", + userCode: "TEST-CODE", + }, + }); + const view = renderNativeAuth(); + expect(tab.location.href).toBe("https://auth.openai.com/device"); + expect(setup.startAuth).toHaveBeenCalledWith({ + environmentId, + input: { instanceId: nativeInstanceId }, + }); + expect(button(view, "Open browser")?.props.disabled).toBe(false); + hooks.reset(); + renderNativeAuth(); + expect(open.mock.calls).toEqual([["", "_blank"]]); + expect(setup.openExternal.mock.calls).toEqual([]); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("opens the native browser method on desktop only after a deliberate sign-in", async () => { + vi.stubGlobal("window", { desktopBridge: {} }); + try { + click(renderNativeAuth(), "Sign in"); + await flushPromises(); + setup.auth = authState({ + instanceId: nativeInstanceId, + phase: "waiting", + flowId: "native-flow", + interaction: { + type: "browser", + id: "native-flow", + url: "https://auth.openai.com/test", + requiresConsent: false, + }, + }); + renderNativeAuth(); + expect(setup.openExternal).toHaveBeenCalledWith("https://auth.openai.com/test"); + renderNativeAuth(); + expect(setup.openExternal.mock.calls).toEqual([["https://auth.openai.com/test"]]); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("closes a reserved tab when sign-in fails before a URL arrives", async () => { + const close = vi.fn(); + const tab = { location: { href: "" }, opener: {}, close, closed: false }; + vi.stubGlobal("window", { open: () => tab }); + try { + click(renderNativeAuth(), "Sign in"); + await flushPromises(); + setup.auth = authState({ + instanceId: nativeInstanceId, + phase: "failed", + flowId: "native-flow", + authorizationUrl: null, + message: "Could not start Codex.", + }); + const view = renderNativeAuth(); + expect(close.mock.calls).toEqual([[]]); + expect(button(view, "Retry sign-in")?.props.disabled).toBe(false); + expect(tab.location.href).toBe(""); + } finally { + vi.unstubAllGlobals(); + } + }); +}); diff --git a/apps/web/src/components/settings/ProviderWizardAuthenticationStep.tsx b/apps/web/src/components/settings/ProviderWizardAuthenticationStep.tsx index 9a68ef2e0c0b..8d960f78a3e1 100644 --- a/apps/web/src/components/settings/ProviderWizardAuthenticationStep.tsx +++ b/apps/web/src/components/settings/ProviderWizardAuthenticationStep.tsx @@ -14,11 +14,13 @@ export function ProviderWizardAuthenticationStep({ environmentLabel, instanceId, onFinish, + autoOpenBrowser = false, }: { readonly environmentId: EnvironmentId; readonly environmentLabel: string; readonly instanceId: ProviderInstanceId; readonly onFinish: () => void; + readonly autoOpenBrowser?: boolean; }) { const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS; @@ -53,6 +55,7 @@ export function ProviderWizardAuthenticationStep({ }, }} readOnly={false} + autoOpenBrowser={autoOpenBrowser} /> ) : ( ({ + ...current, + state: { + ...current.state, + phase: "cancelled" as const, + interaction: null, + authorizationUrl: null, + expiresAt: null, + message: "Sign-in cancelled.", + }, + })); + }), + ); return snapshot.value.state; }).pipe(Effect.uninterruptible), logout: (stopSessions) => From ae173c3655483ccf603791bdee83703e7b9537dd Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Sat, 17 Oct 2026 01:42:28 -0700 Subject: [PATCH 007/408] fix(providers): wait for new instances before subscribing to auth --- packages/client-runtime/src/state/server.ts | 31 ++- .../src/state/serverAuth.test.ts | 221 ++++++++++++++++++ 2 files changed, 247 insertions(+), 5 deletions(-) create mode 100644 packages/client-runtime/src/state/serverAuth.test.ts diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index d0cd59c56e96..f6257434c6f9 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1,5 +1,6 @@ import { type EnvironmentId, + type ProviderInstanceId, type ServerConfig, type ServerConfigStreamEvent, type ServerLifecycleWelcomePayload, @@ -935,6 +936,27 @@ export function createServerEnvironmentAtoms( Atom.withLabel(`environment-data:server:providers:${environmentId}`), ), ); + const providerAuthSubscription = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:provider:auth-subscription", + tag: WS_METHODS.providerAuthSubscribe, + idleTtlMs: 0, + }); + const providerAuthStateFamily = Atom.family((environmentId: EnvironmentId) => + Atom.family((instanceId: ProviderInstanceId) => + Atom.make((get) => { + // Settings save before the server finishes creating the provider's auth controller. + const available = get(providersValueAtom(environmentId))?.some( + (provider) => provider.instanceId === instanceId, + ); + return available + ? get(providerAuthSubscription({ environmentId, input: { instanceId } })) + : AsyncResult.initial(); + }).pipe( + Atom.setIdleTTL(0), + Atom.withLabel(`environment-data:provider:auth-state:${environmentId}:${instanceId}`), + ), + ), + ); const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) => runtime .atom(serverWelcomeStateChanges(environmentId), { initialValue: null }) @@ -983,11 +1005,10 @@ export function createServerEnvironmentAtoms( updateStateAtom, settingsValueAtom, providersValueAtom, - providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, { - label: "environment-data:provider:auth-state", - tag: WS_METHODS.providerAuthSubscribe, - idleTtlMs: 0, - }), + providerAuthState: (target: { + readonly environmentId: EnvironmentId; + readonly input: EnvironmentRpcInput; + }) => providerAuthStateFamily(target.environmentId)(target.input.instanceId), startProviderAuth: createEnvironmentRpcCommand(runtime, { label: "environment-data:provider:auth-start", tag: WS_METHODS.providerAuthStart, diff --git a/packages/client-runtime/src/state/serverAuth.test.ts b/packages/client-runtime/src/state/serverAuth.test.ts new file mode 100644 index 000000000000..695386c8314e --- /dev/null +++ b/packages/client-runtime/src/state/serverAuth.test.ts @@ -0,0 +1,221 @@ +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSetupError, + WS_METHODS, + type ProviderAuthState, + type ServerConfig, + type ServerConfigStreamEvent, + type ServerProvider, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; + +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type PreparedConnection, + type SupervisorConnectionState, +} from "../connection/model.ts"; +import * as EnvironmentRegistry from "../connection/registry.ts"; +import * as EnvironmentSupervisor from "../connection/supervisor.ts"; +import * as Persistence from "../platform/persistence.ts"; +import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; +import type { RpcSession } from "../rpc/session.ts"; +import { createServerEnvironmentAtoms } from "./server.ts"; + +const target = new PrimaryConnectionTarget({ + environmentId: EnvironmentId.make("auth-environment"), + label: "Auth environment", + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", +}); +const instanceId = ProviderInstanceId.make("codex_cli_second"); +const config = { + providers: [], + settings: DEFAULT_SERVER_SETTINGS, + environment: { serverVersion: "0.0.1", capabilities: {} }, +} as unknown as ServerConfig; +const provider: ServerProvider = { + instanceId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "0.156.1", + status: "ready", + auth: { status: "unauthenticated" }, + checkedAt: "2026-10-17T00:00:00.000Z", + models: [], + skills: [], + slashCommands: [], +}; +const idle: ProviderAuthState = { + instanceId, + phase: "idle", + flowId: null, + authorizationUrl: null, + expiresAt: null, + message: null, +}; + +it.effect("waits for a newly configured provider and preserves its active auth subscription", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const auth = yield* SubscriptionRef.make(idle); + const closed = yield* Queue.unbounded(); + let registered = false; + let requests = 0; + const client = { + [WS_METHODS.subscribeServerConfig]: () => + Stream.concat( + Stream.succeed({ version: 1 as const, type: "snapshot" as const, config }), + Stream.fromQueue(events), + ), + [WS_METHODS.providerAuthSubscribe]: () => + Stream.unwrap( + Effect.sync(() => { + requests++; + return registered + ? SubscriptionRef.changes(auth).pipe(Stream.ensuring(Queue.offer(closed, undefined))) + : Stream.fail( + new ProviderSetupError({ + instanceId, + operation: "subscribe", + detail: "This provider instance is no longer available.", + }), + ); + }), + ), + } as unknown as WsRpcProtocolClient; + const session: RpcSession = { + client, + initialConfig: Effect.succeed(config), + subscribeServerConfig: (input) => client.subscribeServerConfig(input), + ready: Effect.void, + probe: Effect.void, + closed: Effect.never, + }; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target, + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected", + }), + session: yield* SubscriptionRef.make(Option.some(session)), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + const environments = EnvironmentRegistry.EnvironmentRegistry.of({ + run: (_environmentId, effect) => + Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + followStream: (_environmentId, stream) => + Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + } as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.merge( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments), + Layer.mock(Persistence.EnvironmentCacheStore)({ + loadServerConfig: () => Effect.succeedNone, + saveServerConfig: () => Effect.void, + }), + ), + ); + const initialConfigValueAtom = Atom.make(config); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => initialConfigValueAtom, + }); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) => + Effect.sync(() => value.dispose()), + ); + const authAtom = atoms.providerAuthState({ + environmentId: target.environmentId, + input: { instanceId }, + }); + const observed = yield* Queue.unbounded>(); + yield* AtomRegistry.toStream(registry, authAtom).pipe( + Stream.runForEach((value) => Queue.offer(observed, value)), + Effect.forkScoped, + ); + + const settings = { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [instanceId]: { driver: provider.driver, config: { setupMode: "cli" } }, + }, + }; + yield* Queue.offer(events, { version: 1, type: "settingsUpdated", payload: { settings } }); + yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(target.environmentId)).pipe( + Stream.filter((value) => value === settings), + Stream.runHead, + ); + expect(requests).toBe(0); + expect(AsyncResult.isInitial(registry.get(authAtom))).toBe(true); + + registered = true; + yield* Queue.offer(events, { + version: 1, + type: "providerStatuses", + payload: { providers: [provider] }, + }); + const nextSuccess = Stream.fromQueue(observed).pipe( + Stream.filter(AsyncResult.isSuccess), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect((yield* nextSuccess).value).toEqual(idle); + expect(requests).toBe(1); + + const waiting: ProviderAuthState = { + ...idle, + phase: "waiting", + flowId: "native-login", + authorizationUrl: "https://auth.openai.com/device", + }; + yield* SubscriptionRef.set(auth, waiting); + expect((yield* nextSuccess).value).toEqual(waiting); + const updated = { ...provider, displayName: "Second account" }; + yield* Queue.offer(events, { + version: 1, + type: "providerStatuses", + payload: { providers: [updated] }, + }); + yield* AtomRegistry.toStream(registry, atoms.providersValueAtom(target.environmentId)).pipe( + Stream.filter((value) => value?.[0]?.displayName === updated.displayName), + Stream.runHead, + ); + expect(requests).toBe(1); + expect(registry.get(authAtom)).toMatchObject({ _tag: "Success", value: waiting }); + + const succeeded: ProviderAuthState = { ...idle, phase: "succeeded", flowId: waiting.flowId }; + yield* SubscriptionRef.set(auth, succeeded); + expect((yield* nextSuccess).value).toEqual(succeeded); + + registered = false; + yield* Queue.offer(events, { + version: 1, + type: "providerStatuses", + payload: { providers: [] }, + }); + yield* Queue.take(closed); + expect(AsyncResult.isInitial(registry.get(authAtom))).toBe(true); + registered = true; + yield* SubscriptionRef.set(auth, idle); + yield* Queue.offer(events, { + version: 1, + type: "providerStatuses", + payload: { providers: [provider] }, + }); + expect((yield* nextSuccess).value).toEqual(idle); + expect(requests).toBe(2); + }), +); From 15f6084505d66d277fca7e15d34aa9373432261a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Sat, 17 Oct 2026 01:50:55 -0700 Subject: [PATCH 008/408] fix(web): simplify Codex connection choices --- ...roviderInstanceDialog.environment.test.tsx | 151 ++++++++++++-- .../settings/AddProviderInstanceDialog.tsx | 185 ++++++++++++------ 2 files changed, 262 insertions(+), 74 deletions(-) diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx index b744b59bf0d9..755848d1a8f0 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx @@ -134,10 +134,30 @@ function button(dialog: unknown, label: string) { return element; } +function selectCodexConnection(dialog: unknown, choice: "cli" | "existing" | "managed") { + const group = visitElements( + dialog, + (element) => element.props["aria-labelledby"] === "add-codex-connection-label", + ); + expect(group).not.toBeNull(); + (group!.props.onValueChange as (value: string) => void)(choice); +} + +function openCodexConnection(dialog = renderDialog()) { + (button(dialog, "Next").props.onClick as () => void)(); + return renderDialog(); +} + +function continueCodexConnection(dialog: unknown) { + (button(dialog, "Continue").props.onClick as () => void)(); + return renderDialog(); +} + function prepareInstance() { - let dialog = renderDialog(); - (button(dialog, "Use existing Codex CLI").props.onClick as () => void)(); + let dialog = openCodexConnection(); + selectCodexConnection(dialog, "existing"); dialog = renderDialog(); + dialog = continueCodexConnection(dialog); const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work"); if (!label) throw new Error("Missing instance label input."); (label.props.onChange as (event: { target: { value: string } }) => void)({ @@ -186,9 +206,9 @@ describe("AddProviderInstanceDialog environment routing", () => { codex_2: { driver: "codex", enabled: false }, }, }); - let tree = render(); - (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); - tree = render(); + let tree = openCodexConnection(render()); + selectCodexConnection(tree, "existing"); + tree = continueCodexConnection(render()); (findByChildren(tree, "Next").props.onClick as () => void)(); tree = render(); (findByChildren(tree, "Add instance").props.onClick as () => void)(); @@ -212,9 +232,101 @@ describe("AddProviderInstanceDialog environment routing", () => { expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId); }); - it("creates a native Codex account without runtime overrides and continues to sign-in", async () => { - (button(renderDialog(), "Sign in with Codex CLI").props.onClick as () => void)(); + it("keeps Codex connection choices separate from the provider catalog and remembers selection on Back", () => { let tree = renderDialog(); + const stepper = visitElements( + tree, + (element) => + typeof element.type === "function" && + element.type.name === "AddProviderInstanceWizardSteps", + ); + expect(stepper?.props.disabled).toBe(true); + expect( + visitElements( + tree, + (element) => element.props["aria-labelledby"] === "add-codex-connection-label", + ), + ).toBeNull(); + expect( + visitElements( + tree, + (element) => + typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep", + ), + ).not.toBeNull(); + + tree = openCodexConnection(tree); + const header = visitElements( + tree, + (element) => typeof element.type === "function" && element.type.name === "WizardHeader", + ); + expect(header?.props.title).toBe("Connect Codex"); + const connectionGroup = visitElements( + tree, + (element) => element.props["aria-labelledby"] === "add-codex-connection-label", + ); + expect(connectionGroup?.props.value).toBe("cli"); + expect( + visitElements( + tree, + (element) => + element.props.value === "managed" && + element.props["aria-label"] === + "Use ChatGPT sharing. Share through ChatGPT; some native Codex features are unavailable.", + ), + ).not.toBeNull(); + expect( + visitElements( + tree, + (element) => + typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep", + ), + ).toBeNull(); + + selectCodexConnection(tree, "existing"); + tree = renderDialog(); + (button(tree, "Back").props.onClick as () => void)(); + tree = renderDialog(); + expect( + visitElements( + tree, + (element) => element.props["aria-labelledby"] === "add-instance-driver-label", + ), + ).not.toBeNull(); + tree = openCodexConnection(tree); + const rememberedGroup = visitElements( + tree, + (element) => element.props["aria-labelledby"] === "add-codex-connection-label", + ); + expect(rememberedGroup?.props.value).toBe("existing"); + expect(button(tree, "Continue").props.disabled).not.toBe(true); + }); + + it("opens ChatGPT sharing only after Continue", () => { + let tree = openCodexConnection(); + selectCodexConnection(tree, "managed"); + tree = renderDialog(); + expect( + visitElements( + tree, + (element) => + typeof element.type === "function" && + element.type.name === "AddManagedCodexAccountDialog", + ), + ).toBeNull(); + + (button(tree, "Continue").props.onClick as () => void)(); + tree = renderDialog(); + const managedDialog = visitElements( + tree, + (element) => + typeof element.type === "function" && element.type.name === "AddManagedCodexAccountDialog", + ); + expect(managedDialog?.props.environmentId).toBe(remoteEnvironmentId); + }); + + it("creates a native Codex account without runtime overrides and continues to sign-in", async () => { + let tree = continueCodexConnection(openCodexConnection()); const label = visitElements(tree, (entry) => entry.props.placeholder === "e.g. Work")!; (label.props.onChange as (event: { target: { value: string } }) => void)({ target: { value: "Personal" }, @@ -246,11 +358,14 @@ describe("AddProviderInstanceDialog environment routing", () => { }); it("preserves the existing CLI configuration after leaving the native account path", async () => { - (button(renderDialog(), "Sign in with Codex CLI").props.onClick as () => void)(); - (button(renderDialog(), "Back").props.onClick as () => void)(); - (button(renderDialog(), "Use existing Codex CLI").props.onClick as () => void)(); - (button(renderDialog(), "Next").props.onClick as () => void)(); - (button(renderDialog(), "Add instance").props.onClick as () => void)(); + let tree = continueCodexConnection(openCodexConnection()); + (button(tree, "Back").props.onClick as () => void)(); + tree = renderDialog(); + selectCodexConnection(tree, "existing"); + tree = continueCodexConnection(renderDialog()); + (button(tree, "Next").props.onClick as () => void)(); + tree = renderDialog(); + (button(tree, "Add instance").props.onClick as () => void)(); await Promise.resolve(); expect(settingsHooks.mutate).toHaveBeenCalledWith({ operation: "create", @@ -471,9 +586,9 @@ describe("AddProviderInstanceDialog environment routing", () => { }); it("restores the manual Codex draft after choosing Traex and switching back", async () => { - let tree = render(); - (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); - tree = render(); + let tree = openCodexConnection(render()); + selectCodexConnection(tree, "existing"); + tree = continueCodexConnection(render()); const label = visitElements(tree, (element) => element.props.id === "add-provider-label"); (label!.props.onChange as (event: { target: { value: string } }) => void)({ target: { value: "Work" }, @@ -492,6 +607,8 @@ describe("AddProviderInstanceDialog environment routing", () => { tree = render(); (findByChildren(tree, "Back").props.onClick as () => void)(); tree = render(); + (findByChildren(tree, "Back").props.onClick as () => void)(); + tree = render(); selectTraex(tree); tree = render(); (findByChildren(tree, "Back").props.onClick as () => void)(); @@ -502,8 +619,8 @@ describe("AddProviderInstanceDialog environment routing", () => { ); (group!.props.onValueChange as (value: string) => void)("codex"); tree = render(); - (findByChildren(tree, "Use existing Codex CLI").props.onClick as () => void)(); - tree = render(); + tree = openCodexConnection(tree); + tree = continueCodexConnection(tree); (findByChildren(tree, "Next").props.onClick as () => void)(); tree = render(); (findByChildren(tree, "Add instance").props.onClick as () => void)(); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index dd53057181f9..cff68de7e110 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -3,7 +3,7 @@ import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { Radio as RadioPrimitive } from "@base-ui/react/radio"; -import { CheckIcon } from "lucide-react"; +import { CheckIcon, HardDriveIcon, MessageCircleIcon, TerminalIcon } from "lucide-react"; import { useMemo, useState } from "react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { @@ -25,7 +25,6 @@ import { cn } from "../../lib/utils"; import { normalizeProviderAccentColor } from "../../providerInstances"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { Button } from "../ui/button"; -import { ChatGptConnectionButton } from "./ChatGptConnectionButton"; import { Dialog } from "../ui/dialog"; import { Badge } from "../ui/badge"; import { Input } from "../ui/input"; @@ -85,6 +84,27 @@ const PROVIDER_OPTIONS = [ .map((option) => ({ ...option, value: option.driverKind })), { ...DEFAULT_DRIVER_OPTION, value: TRAEX_BRIDGE_PRESET, label: "Traex" }, ]; +type CodexConnectionChoice = "cli" | "existing" | "managed"; +const CODEX_CONNECTION_OPTIONS = [ + { + value: "cli", + label: "Sign in with Codex CLI", + description: "Independent account with shared skills, plugins, and history.", + icon: TerminalIcon, + }, + { + value: "existing", + label: "Use existing Codex CLI", + description: "Reuse the CLI account and runtime configured here.", + icon: HardDriveIcon, + }, + { + value: "managed", + label: "Use ChatGPT sharing", + description: "Share through ChatGPT; some native Codex features are unavailable.", + icon: MessageCircleIcon, + }, +] as const; const EMPTY_CONFIG_DRAFT: Record = {}; /** * Validate an instance id against the same slug rules the server applies in @@ -120,6 +140,8 @@ export function AddProviderInstanceDialog({ const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); const [wizardStep, setWizardStep] = useState(0); + const [providerView, setProviderView] = useState<"catalog" | "codexConnection">("catalog"); + const [codexConnectionChoice, setCodexConnectionChoice] = useState("cli"); const [codexSetupMode, setCodexSetupMode] = useState<"cli" | "existing" | "managed" | null>(null); const [selection, setSelection] = useState(DEFAULT_DRIVER_KIND); const driver = @@ -394,10 +416,16 @@ export function AddProviderInstanceDialog({ return ( - + Add an account or configure a provider on {environmentLabel}.} + title={providerView === "codexConnection" ? "Connect Codex" : "Add provider"} + description={ + providerView === "codexConnection" ? ( + <>Choose how Codex connects to {environmentLabel}. + ) : ( + <>Add an account or configure a provider on {environmentLabel}. + ) + } > {isAcpRegistry ? ( )} @@ -436,7 +477,12 @@ export function AddProviderInstanceDialog({ className={cn(isAcpRegistry && wizardStep === identityStep && "min-h-72")} holdHeight={wizardStep === 0 && !isManualAcpConfiguration && isRegistryLoading} > -
+
Provider
@@ -484,55 +530,56 @@ export function AddProviderInstanceDialog({
- {wizardStep === 0 && selection === "codex" ? ( -
-
- -

- Add an independent Codex account. Keep your shared skills, plugins, and thread - history. -

-
-
- -

- Use the CLI account and runtime already configured on {environmentLabel}. -

-
-
- setCodexSetupMode("managed")} - > - Use ChatGPT sharing - -

- Connect through ChatGPT subscription sharing. Some native Codex features are - unavailable. -

+ {wizardStep === 0 && providerView === "codexConnection" ? ( +
+
+ Connection method
+ { + if (value === "cli" || value === "existing" || value === "managed") { + setCodexConnectionChoice(value); + } + }} + > + {CODEX_CONNECTION_OPTIONS.map((option) => { + const Icon = option.icon; + return ( + + + + + {option.label} + + + {option.description} + + + + + {codexConnectionChoice === option.value ? ( + + ) : null} + + + + ); + })} +
) : null} - {wizardStep === 0 ? ( + {wizardStep === 0 && providerView === "catalog" ? (
@@ -731,21 +778,45 @@ export function AddProviderInstanceDialog({ - {wizardStep === 0 && selection === "codex" ? null : wizardStep < - (isAcpRegistry || isCliAccount ? 1 : 2) ? ( + {wizardStep === 0 ? ( + + ) : wizardStep < (isAcpRegistry || isCliAccount ? 1 : 2) ? (
- {wizardStep === 0 && providerView === "codexConnection" ? ( + {wizardStep === 0 && providerView === "connection" ? (
Connection method
{ if (value === "cli" || value === "existing" || value === "managed") { - setCodexConnectionChoice(value); + setConnectionChoices((current) => ({ ...current, [selection]: value })); } }} > - {CODEX_CONNECTION_OPTIONS.map((option) => { + {connectionOptions.map((option) => { const Icon = option.icon; return ( - {codexConnectionChoice === option.value ? ( + {connectionChoice === option.value ? ( ) : null} @@ -783,7 +802,7 @@ export function AddProviderInstanceDialog({ disabled={isSaving || isPreparingRegistryAgent} onClick={() => { if (wizardStep === 0) { - if (providerView === "codexConnection") { + if (providerView === "connection") { setProviderView("catalog"); return; } @@ -800,21 +819,19 @@ export function AddProviderInstanceDialog({ size="sm" disabled={isPreparingRegistryAgent} onClick={() => { - if (providerView === "codexConnection") { - setCodexSetupMode(codexConnectionChoice); - if (codexConnectionChoice !== "managed") { - setWizardStep(1); - } + if (providerView === "connection") { + if (connectionChoice === "managed") setProviderView("managed"); + else setWizardStep(1); return; } - if (selection === "codex") { - setProviderView("codexConnection"); + if (hasConnectionChoice) { + setProviderView("connection"); return; } navigateToStep(wizardStep + 1); }} > - {providerView === "codexConnection" ? "Continue" : "Next"} + {providerView === "connection" ? "Continue" : "Next"} ) : wizardStep < (isAcpRegistry || isCliAccount ? 1 : 2) ? (
diff --git a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx index 44fb6db76996..5eb916c64c9d 100644 --- a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx +++ b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx @@ -10,6 +10,7 @@ import type { ProviderInstanceId, ServerProvider, } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; import { lazy, Suspense, useEffect, useRef, useState } from "react"; import { CopyIcon } from "lucide-react"; @@ -50,6 +51,19 @@ export function ProviderAuthenticationSection({ const complete = useAtomCommand(serverEnvironment.completeProviderAuth, commands); const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, commands); const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, commands); + const canInstallCodex = provider.driver === "codex" && provider.setup?.canInstall === true; + const installQuery = useEnvironmentQuery( + canInstallCodex ? serverEnvironment.providerInstallState(target) : null, + ); + const startInstall = useAtomCommand(serverEnvironment.startProviderInstall, commands); + const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, commands); + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, commands); + const canStartInstall = useAtomValue( + serverEnvironment.startProviderInstall.permissionAtom(environmentId), + ); + const canCancelInstall = useAtomValue( + serverEnvironment.cancelProviderInstall.permissionAtom(environmentId), + ); const [methodId, setMethodId] = useState(""); const [draft, setDraft] = useState({ id: "", values: {} as Record }); const [error, setError] = useState(null); @@ -58,6 +72,8 @@ export function ProviderAuthenticationSection({ const reservedBrowser = useRef(null); const [browserFlowId, setBrowserFlowId] = useState(null); const handledBrowserFlow = useRef(null); + const refreshedInstallation = useRef(null); + const installation = installQuery.data; const terminalQueue = useRef([]); const terminalSending = useRef(false); const auth = query.data; @@ -65,6 +81,14 @@ export function ProviderAuthenticationSection({ const acceptsCode = interaction?.type === "browser" && interaction.callbackInputKind === "code"; const active = auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying"; + const installActive = + installation?.phase === "downloading" || + installation?.phase === "extracting" || + installation?.phase === "verifying"; + const installationKey = + installation?.phase === "succeeded" && installation.source === "managed" + ? `${installation.operationId ?? ""}:${installation.installedVersion ?? ""}:${installation.executablePath ?? ""}` + : null; const signedIn = provider.auth.status === "authenticated" || (provider.auth.status === "unknown" && auth?.phase === "succeeded"); @@ -91,13 +115,23 @@ export function ProviderAuthenticationSection({ : "Finish signing in in your browser." : signedIn ? "Signed in." - : isDiscovering - ? "Discovering sign-in methods…" - : needsExternalSetup - ? "No in-app sign-in advertised. Follow the provider's docs to finish setup." - : `Sign in on ${environmentLabel}.`; + : canInstallCodex && !provider.installed + ? "Install Codex CLI on this environment before signing in." + : isDiscovering + ? "Discovering sign-in methods…" + : needsExternalSetup + ? "No in-app sign-in advertised. Follow the provider's docs to finish setup." + : `Sign in on ${environmentLabel}.`; const statusMessage = auth?.phase === "failed" ? auth.message : null; const disabled = readOnly || pending || query.error !== null || isDiscovering; + const installDisabled = + readOnly || pending || !canStartInstall || installQuery.error !== null || installation === null; + const cancelInstallDisabled = + readOnly || + pending || + !canCancelInstall || + installQuery.error !== null || + installation === null; const draftId = `${auth?.flowId ?? ""}:${interaction?.id ?? ""}`; const values = draft.id === draftId ? draft.values : {}; const url = @@ -105,6 +139,23 @@ export function ProviderAuthenticationSection({ ? interaction.url : auth?.authorizationUrl; + useEffect(() => { + if (!canInstallCodex || provider.installed || installationKey === null) { + refreshedInstallation.current = null; + return; + } + if (refreshedInstallation.current === installationKey) return; + refreshedInstallation.current = installationKey; + void refreshProviders({ environmentId, input: { instanceId } }); + }, [ + canInstallCodex, + environmentId, + instanceId, + installationKey, + provider.installed, + refreshProviders, + ]); + useEffect(() => () => reservedBrowser.current?.close(), []); useEffect(() => { if (!browserFlowId || handledBrowserFlow.current === browserFlowId) return; @@ -159,7 +210,10 @@ export function ProviderAuthenticationSection({ } } - async function run(command: () => Promise>) { + async function run( + command: () => Promise>, + failureMessage = "Provider sign-in failed. Try again.", + ) { if (pendingRef.current) return false; pendingRef.current = true; setPending(true); @@ -170,12 +224,10 @@ export function ProviderAuthenticationSection({ if (result._tag === "Success") succeeded = true; else if (!isAtomCommandInterrupted(result)) { const failure = squashAtomCommandFailure(result); - setError( - failure instanceof Error ? failure.message : "Provider sign-in failed. Try again.", - ); + setError(failure instanceof Error ? failure.message : failureMessage); } } catch { - setError("Provider sign-in failed. Try again."); + setError(failureMessage); } pendingRef.current = false; setPending(false); @@ -217,6 +269,21 @@ export function ProviderAuthenticationSection({ setDraft({ id: draftId, values: { ...values, [name]: value } }); } + const installStatus = + installation?.phase === "downloading" + ? `Downloading Codex CLI (${(installation.downloadedBytes / 1_000_000).toFixed(1)} MB${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)} MB`}).` + : installation?.phase === "extracting" + ? "Extracting Codex CLI." + : installation?.phase === "verifying" + ? "Checking Codex CLI." + : installation?.phase === "succeeded" && installation.source === "local" + ? "This provider cannot use the environment's Codex executable. Install Codex CLI for this provider." + : installation?.phase === "succeeded" && !provider.installed + ? "Installation finished. Checking this provider's Codex runtime." + : installation?.phase === "failed" || installation?.phase === "cancelled" + ? (installation.message ?? "Codex CLI installation failed.") + : null; + return ( {statusMessage}

+ ) : installQuery.error || (canInstallCodex && !provider.installed && installStatus) ? ( +
+

+ {installQuery.error ?? installStatus} +

+ {installation?.phase === "downloading" && + installation.totalBytes !== null && + installation.totalBytes > 0 ? ( + + ) : null} +
) : undefined } control={
+ {canInstallCodex && !provider.installed ? ( + installActive ? ( + installation.operationId ? ( + + ) : ( + + ) + ) : ( + + ) + ) : null} {!active && (auth?.methods?.length ?? 0) > 1 ? ( setUrl(event.target.value)} + placeholder="https://box.example.ts.net" + disabled={busy} + autoFocus + nativeInput + spellCheck={false} + /> + + +
+ + What agents here may do there + + setAccess(value as AuthMcpClientAccess)} + > + {AuthMcpClientAccess.literals.map((option) => ( + + ))} + +

+ An agent here never gets more there than its own mode here either. Threads it starts + there cannot change that environment's own threads, projects or settings. +

+
+ + + + + + + + + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 82995946155f..6f077d0506a1 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -113,10 +113,29 @@ describe("searchSettings", () => { "auto-settle-inactive-threads", "auto-settle-merged-threads", "days-before-auto-settle", + "linked-environments", ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); + it("offers Linked environments only when a connected environment shows its links", () => { + const availability = { + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + hasMacProviderSettingsEnvironment: false, + canManageLocalBackend: true, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: false, + }; + const itemIds = (hasPeerLinkHost: boolean) => + filterAvailableSettingsSearchItems({ ...availability, hasPeerLinkHost }).map( + (item) => item.id, + ); + expect(itemIds(false)).not.toContain("linked-environments"); + expect(itemIds(true)).toContain("linked-environments"); + }); + it("finds keybinding commands by label, command id, and default key", () => { expect(searchSettings("toggle sidebar")[0]?.id).toBe("keybinding-sidebar.toggle"); expect(searchSettings("sidebar.toggle")[0]?.id).toBe("keybinding-sidebar.toggle"); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index c7c5f26ae90d..76b3c3c96591 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -55,6 +55,9 @@ export interface SettingsSearchItem { readonly localEnvironmentOnly?: boolean; readonly wslAvailableOnly?: boolean; readonly managedTunnelOnly?: boolean; + // Its section only renders for a connected environment with peer links that + // lets this session read its links. + readonly peerLinksOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; } @@ -69,6 +72,7 @@ export interface SettingsSearchAvailability { readonly isWslSettingsRowVisible: boolean; readonly hasThreadAutoSettlement: boolean; readonly managedTunnelActive?: boolean; + readonly hasPeerLinkHost?: boolean; } export const SETTINGS_SECTION_LABELS: Readonly> = { @@ -974,6 +978,14 @@ export const SETTINGS_SEARCH_ITEMS = [ "connections server backend local remote access administrative permissions scope pairing links qr code authorized clients sessions revoke endpoint", ], }, + { + id: "linked-environments", + peerLinksOnly: true, + title: "Linked environments", + to: "/settings/connections", + targetId: "linked-environments", + searchTerms: ["link peer another machine vps agents work there handoff pairing code"], + }, { id: "remote-environments", title: "Environments", @@ -1132,7 +1144,8 @@ export function filterAvailableSettingsSearchItems( (!item.localEnvironmentOnly || !availability.localEnvironmentDisabled) && (!item.wslAvailableOnly || availability.isWslSettingsRowVisible) && (!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) && - (!item.managedTunnelOnly || availability.managedTunnelActive === true), + (!item.managedTunnelOnly || availability.managedTunnelActive === true) && + (!item.peerLinksOnly || availability.hasPeerLinkHost === true), ); } diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index 924b548515f9..6c8a9fea2ee9 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -6,6 +6,7 @@ import { isElectron } from "~/env"; import { isLocalEnvironmentDisabled } from "~/localEnvironment"; import { desktopWslStateAtom } from "~/state/desktopWslState"; import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments"; +import { usePeerLinkHosts } from "~/state/peerLinks"; import { useEnvironmentQuery } from "~/state/query"; import { useEnvironmentScope } from "~/state/session"; import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic"; @@ -45,6 +46,7 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope); + const hasPeerLinkHost = usePeerLinkHosts().length > 0; const cloudLinkState = usePrimaryCloudLinkState().data; // Same fallback as the Connections row: older servers imply a tunnel from `linked`. const managedTunnelActive = @@ -69,5 +71,6 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch isWslSettingsRowVisible: wslSettingsRowVisible, hasThreadAutoSettlement, managedTunnelActive, + hasPeerLinkHost, }); } diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts new file mode 100644 index 000000000000..a6534f6262de --- /dev/null +++ b/apps/web/src/state/peerLinks.ts @@ -0,0 +1,20 @@ +import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; +import { AuthAccessReadScope } from "@t3tools/contracts"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { useEnvironments } from "./environments"; +import { useEnvironmentsWithScope } from "./session"; + +export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime); + +/** Connected environments whose links this session may see, in catalog order. */ +export function usePeerLinkHosts() { + const { environments } = useEnvironments(); + const supported = environments.filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.peerLinks === true, + ); + const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope); + return supported.filter((environment) => readable.has(environment.environmentId)); +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 493a580d14c5..0665a9362247 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -246,6 +246,24 @@ Claude Code, Codex, ChatGPT and other agents T3 Code did not start can drive threads on an environment through its MCP server. See [outside agents](./outside-agents.md) for setup. +## Link another environment + +Link two machines, such as your laptop and a VPS, and agents on one can launch, +message, wait on and stop threads on the other. On the machine you will work +from, open **Settings → Connections → Linked environments**, choose **Link**, +and enter the other machine's address and a pairing code from it. From a +terminal, use `t3 environment link
--pairing-code --access `. + +- The access you pick is the most agents from this machine may do there. An + agent also never gets more there than its own mode here. +- Threads a link starts are marked **From** and this machine's name there. + They can change only other threads the same link started, not that machine's + own threads, projects or settings, and they skip its project setup scripts. +- The link shows up in that machine's **Settings → Connections** like any + outside agent. Revoke it there to end it. **Forget** on this machine only + removes it here. +- Links last 30 days. Link again with a new pairing code to renew one. + ## Manage or revoke access On the host, **Settings → Connections** lets authorized administrators create diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index cb03114c8f40..2bfcb017090b 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -199,6 +199,10 @@ "types": "./src/state/deviceHubAccess.ts", "default": "./src/state/deviceHubAccess.ts" }, + "./state/peerLinks": { + "types": "./src/state/peerLinks.ts", + "default": "./src/state/peerLinks.ts" + }, "./state/preview": { "types": "./src/state/preview.ts", "default": "./src/state/preview.ts" diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 09927e38398a..6a916a95af41 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -7,6 +7,7 @@ import type { RpcSession } from "../rpc/session.ts"; import { describe, expect, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import { + AuthAccessWriteScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, AuthPreviewOperateScope, @@ -291,6 +292,33 @@ it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] ), ); +it.effect("requires access management to link or forget environments", () => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + registry.set(sessions(env), AsyncResult.success(grant(true))); + for (const method of [WS_METHODS.peerLinksLink, WS_METHODS.peerLinksUnlink]) { + const peerLinks = createCommandPermissions(runtime, method); + expect(registry.get(peerLinks.permissionAtom(env))).toBe(false); + expect( + (yield* peerLinks.authorize(registry, env).pipe(Effect.flip)).requiredPermission, + ).toBe(AuthAccessWriteScope); + } + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthAccessWriteScope], + permissions: [AuthAccessWriteScope], + }), + ); + const link = createCommandPermissions(runtime, WS_METHODS.peerLinksLink); + expect(registry.get(link.permissionAtom(env))).toBe(true); + yield* link.authorize(registry, env); + }), + ), +); + it.effect("honors exact empty permissions and preserves legacy parent grants", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index ba78e2304d75..a9feae74f6ea 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -100,6 +100,8 @@ export interface EnvironmentThreadShell { readonly worktreePath: string | null; readonly lineage: OrchestrationV2ThreadShell["lineage"]; readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"]; + /** The linked environment that started this thread here, when one did. */ + readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null; readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; readonly latestRun: ThreadRunSummary | null; readonly runtime: ThreadRuntimeSummary | null; @@ -246,6 +248,7 @@ export function presentThreadShell( branchPullRequest: thread.branchPullRequest ?? null, lineage: thread.lineage, forkedFrom: thread.forkedFrom, + linkOrigin: thread.linkOrigin ?? null, activeProviderThreadId: thread.activeProviderThreadId, latestRun, runtime, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts new file mode 100644 index 000000000000..4a02b2a618d2 --- /dev/null +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -0,0 +1,48 @@ +import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { peerLinkHealth } from "./peerLinks.ts"; + +const now = DateTime.makeUnsafe("2026-10-06T12:00:00.000Z"); +const link = (overrides: Partial): PeerLinkSummary => ({ + environmentId: EnvironmentId.make("environment-box"), + label: "Box", + urls: ["https://box.example.ts.net"], + access: "auto", + linkedAt: DateTime.makeUnsafe("2026-09-20T12:00:00.000Z"), + expiresAt: DateTime.makeUnsafe("2026-10-20T12:00:00.000Z"), + lastReachedAt: now, + lastError: null, + status: "reachable", + ...overrides, +}); + +describe("peerLinkHealth", () => { + it("warns only in the last days before a link expires", () => { + expect(peerLinkHealth(link({}), now)).toEqual({ kind: "reachable", expiresInDays: null }); + expect( + peerLinkHealth(link({ expiresAt: DateTime.makeUnsafe("2026-10-09T00:00:00.000Z") }), now), + ).toEqual({ kind: "reachable", expiresInDays: 3 }); + }); + + it("treats a link past its expiry as expired even if the server listed it earlier", () => { + expect( + peerLinkHealth(link({ expiresAt: DateTime.makeUnsafe("2026-10-06T11:00:00.000Z") }), now), + ).toEqual({ kind: "expired" }); + expect(peerLinkHealth(link({ status: "expired" }), now)).toEqual({ kind: "expired" }); + }); + + it("carries why an unreachable link failed last", () => { + expect( + peerLinkHealth(link({ status: "unreachable", lastError: "Box stopped answering." }), now), + ).toEqual({ kind: "unreachable", detail: "Box stopped answering." }); + }); + + it("flags a reachable link whose last call failed, such as after the peer revoked it", () => { + expect(peerLinkHealth(link({ lastError: "Box rejected the link's session." }), now)).toEqual({ + kind: "failing", + detail: "Box rejected the link's session.", + }); + }); +}); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts new file mode 100644 index 000000000000..2dbaf0d9893e --- /dev/null +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -0,0 +1,61 @@ +import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import { Atom } from "effect/reactivity"; + +import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; + +/** Links to other environments, kept by one environment's server. */ +export function createPeerLinkEnvironmentAtoms( + runtime: Atom.AtomRuntime, +) { + const list = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:peer-links:list", + tag: WS_METHODS.peerLinksList, + // Listing probes every linked environment, so a list stays fresh briefly. + staleTimeMs: 10_000, + }); + return { + list, + link: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:link", + tag: WS_METHODS.peerLinksLink, + onSuccess: ({ environmentId }, registry) => + Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + }), + unlink: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:unlink", + tag: WS_METHODS.peerLinksUnlink, + onSuccess: ({ environmentId }, registry) => + Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + }), + }; +} + +/** Links expire after 30 days and cannot be renewed yet, so warn this long before. */ +const EXPIRY_WARNING_DAYS = 5; + +export type PeerLinkHealth = + | { readonly kind: "reachable"; readonly expiresInDays: number | null } + | { readonly kind: "unreachable"; readonly detail: string | null } + | { readonly kind: "failing"; readonly detail: string } + | { readonly kind: "expired" }; + +/** + * What a link's row says about it. `expiresInDays` is set only inside the + * warning window, while the link still works but has to be renewed soon. + * Listing only checks that the peer answers, so a link whose last call failed + * (the peer revoked it, say) is `failing` with the recorded reason; the next + * successful call clears it. + */ +export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth { + if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) { + return { kind: "expired" }; + } + if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError }; + if (link.lastError !== null) return { kind: "failing", detail: link.lastError }; + const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt))); + return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null }; +} diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index f9eaedb48bd7..1981d490776f 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -1,6 +1,7 @@ import * as Schema from "effect/Schema"; import { GitPreparePullRequestThreadInput, GitRunStackedActionInput } from "./git.ts"; import { + AuthAccessWriteScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, AuthPreviewOperateScope, @@ -49,6 +50,9 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, + + [WS_METHODS.peerLinksLink]: AuthAccessWriteScope, + [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; From 66806f18563e696eca958468fb26a62a22d0c4d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:46:22 -0700 Subject: [PATCH 116/408] docs: what agents may do on a linked machine, by the link's access Co-Authored-By: Claude Opus 5.5 --- docs/user/remote-access.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 0665a9362247..ce0934b6762f 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -248,17 +248,21 @@ threads on an environment through its MCP server. See ## Link another environment -Link two machines, such as your laptop and a VPS, and agents on one can launch, -message, wait on and stop threads on the other. On the machine you will work -from, open **Settings → Connections → Linked environments**, choose **Link**, -and enter the other machine's address and a pairing code from it. From a -terminal, use `t3 environment link
--pairing-code --access `. +Link two machines, such as your laptop and a VPS, and agents on one can work on +the other: launch, message, wait on and stop its threads, answer their +questions, and manage its queues, projects and scheduled tasks. On the machine +you will work from, open **Settings → Connections → Linked environments**, +choose **Link**, and enter the other machine's address and a pairing code from +it. From a terminal, use +`t3 environment link
--pairing-code --access `. - The access you pick is the most agents from this machine may do there. An agent also never gets more there than its own mode here. - Threads a link starts are marked **From** and this machine's name there. - They can change only other threads the same link started, not that machine's - own threads, projects or settings, and they skip its project setup scripts. +- A full-access link works there like that machine's own agents. Below full + access, the link's agents can change only threads it started, not that + machine's own threads, projects or settings, and they skip its project setup + scripts. - The link shows up in that machine's **Settings → Connections** like any outside agent. Revoke it there to end it. **Forget** on this machine only removes it here. From a26f5fdb5cb979a5f222053145e7d9a2f3aba4ac Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 13:22:58 +0000 Subject: [PATCH 117/408] test(client-runtime): exercise permitted peer link lifecycle --- .../settings/settingsSearch.test.ts | 22 ++- .../src/state/commandPermissions.test.ts | 154 +++++++++++++++--- .../src/state/peerLinks.test.ts | 48 ------ 3 files changed, 144 insertions(+), 80 deletions(-) delete mode 100644 packages/client-runtime/src/state/peerLinks.test.ts diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 6f077d0506a1..7d5cdbd05926 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -118,22 +118,30 @@ describe("searchSettings", () => { expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); - it("offers Linked environments only when a connected environment shows its links", () => { + it("finds linked environments on a remote host without local maintenance access", () => { const availability = { hasCloudPublicConfig: false, hasEnvironment: true, hasProviderSettingsEnvironment: true, hasMacProviderSettingsEnvironment: false, - canManageLocalBackend: true, + canManageLocalBackend: false, + localEnvironmentDisabled: true, isWslSettingsRowVisible: false, hasThreadAutoSettlement: false, }; - const itemIds = (hasPeerLinkHost: boolean) => - filterAvailableSettingsSearchItems({ ...availability, hasPeerLinkHost }).map( - (item) => item.id, + const results = (hasPeerLinkHost: boolean) => + searchSettings( + "linked environments", + filterAvailableSettingsSearchItems({ ...availability, hasPeerLinkHost }), ); - expect(itemIds(false)).not.toContain("linked-environments"); - expect(itemIds(true)).toContain("linked-environments"); + expect(results(false).map((item) => item.id)).not.toContain("linked-environments"); + expect(results(true)).toContainEqual( + expect.objectContaining({ + id: "linked-environments", + to: "/settings/connections", + targetId: "linked-environments", + }), + ); }); it("finds keybinding commands by label, command id, and default key", () => { diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 6a916a95af41..86fa95636538 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -7,6 +7,7 @@ import type { RpcSession } from "../rpc/session.ts"; import { describe, expect, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import { + AuthAccessReadScope, AuthAccessWriteScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, @@ -18,8 +19,10 @@ import { ScheduledTaskId, WS_METHODS, type AuthSessionState, + type PeerLinkSummary, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -27,6 +30,8 @@ import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { createCommandPermissions } from "./commandPermissions.ts"; import { createEnvironmentRpcCommand } from "./runtime.ts"; +import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts"; +import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts"; vi.mock("./session.ts", () => ({ createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }), @@ -292,31 +297,130 @@ it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] ), ); -it.effect("requires access management to link or forget environments", () => - Effect.scoped( - Effect.gen(function* () { - const registry = yield* setup; - registry.set(sessions(env), AsyncResult.success(grant(true))); - for (const method of [WS_METHODS.peerLinksLink, WS_METHODS.peerLinksUnlink]) { - const peerLinks = createCommandPermissions(runtime, method); - expect(registry.get(peerLinks.permissionAtom(env))).toBe(false); - expect( - (yield* peerLinks.authorize(registry, env).pipe(Effect.flip)).requiredPermission, - ).toBe(AuthAccessWriteScope); - } - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthAccessWriteScope], - permissions: [AuthAccessWriteScope], - }), - ); - const link = createCommandPermissions(runtime, WS_METHODS.peerLinksLink); - expect(registry.get(link.permissionAtom(env))).toBe(true); - yield* link.authorize(registry, env); - }), - ), +it.effect( + "refreshes linked environments after permitted writes and blocks a read-only session", + () => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + const peer: PeerLinkSummary = { + environmentId: EnvironmentId.make("peer"), + label: "Box", + urls: ["https://box.example.test"], + access: "auto", + linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"), + expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"), + lastReachedAt: null, + lastError: null, + status: "reachable", + }; + let links: ReadonlyArray = []; + const client = { + [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })), + [WS_METHODS.peerLinksLink]: vi.fn(() => + Effect.sync(() => { + links = [peer]; + return peer; + }), + ), + [WS_METHODS.peerLinksUnlink]: vi.fn(() => + Effect.sync(() => { + links = []; + return { removed: true }; + }), + ), + }; + const supervisor = { + target: { environmentId: env }, + session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)), + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected" as const, + }), + } as EnvironmentSupervisor["Service"]; + const peerRuntime = Atom.runtime( + Layer.succeed(EnvironmentRegistry, { + run: (id, effect) => { + expect(id).toBe(env); + return Effect.provideService(effect, EnvironmentSupervisor, supervisor); + }, + followStream: (id, stream) => { + expect(id).toBe(env); + return Stream.provideService(stream, EnvironmentSupervisor, supervisor); + }, + } as EnvironmentRegistry["Service"]), + ); + const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime); + const list = peerLinks.list({ environmentId: env, input: {} }); + registry.mount(list); + const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true }); + const setAccess = (writable: boolean) => + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])], + permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])], + }), + ); + registry.mount(sessions(other)); + registry.set( + sessions(other), + AsyncResult.success({ + ...grant(false), + scopes: [AuthAccessWriteScope], + permissions: [AuthAccessWriteScope], + }), + ); + setAccess(false); + expect(yield* readLinks).toEqual({ links: [] }); + const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access }; + const link = Effect.promise(() => + peerLinks.link.run(registry, { environmentId: env, input: linkInput }), + ); + const unlink = Effect.promise(() => + peerLinks.unlink.run(registry, { + environmentId: env, + input: { environmentId: peer.environmentId }, + }), + ); + expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false); + const deniedLink = yield* link; + expect(deniedLink._tag).toBe("Failure"); + if (deniedLink._tag === "Failure") { + expect(Cause.squash(deniedLink.cause)).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredPermission: AuthAccessWriteScope, + }); + } + expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled(); + setAccess(true); + expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true); + expect((yield* link)._tag).toBe("Success"); + expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput); + expect(yield* readLinks).toEqual({ links: [peer] }); + + setAccess(false); + expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false); + const deniedUnlink = yield* unlink; + expect(deniedUnlink._tag).toBe("Failure"); + if (deniedUnlink._tag === "Failure") { + expect(Cause.squash(deniedUnlink.cause)).toMatchObject({ + _tag: "EnvironmentAuthorizationError", + requiredPermission: AuthAccessWriteScope, + }); + } + expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled(); + expect(yield* readLinks).toEqual({ links: [peer] }); + setAccess(true); + expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true); + expect((yield* unlink)._tag).toBe("Success"); + expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({ + environmentId: peer.environmentId, + }); + expect(yield* readLinks).toEqual({ links: [] }); + }), + ), ); it.effect("honors exact empty permissions and preserves legacy parent grants", () => diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts deleted file mode 100644 index 4a02b2a618d2..000000000000 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; -import { describe, expect, it } from "@effect/vitest"; -import * as DateTime from "effect/DateTime"; - -import { peerLinkHealth } from "./peerLinks.ts"; - -const now = DateTime.makeUnsafe("2026-10-06T12:00:00.000Z"); -const link = (overrides: Partial): PeerLinkSummary => ({ - environmentId: EnvironmentId.make("environment-box"), - label: "Box", - urls: ["https://box.example.ts.net"], - access: "auto", - linkedAt: DateTime.makeUnsafe("2026-09-20T12:00:00.000Z"), - expiresAt: DateTime.makeUnsafe("2026-10-20T12:00:00.000Z"), - lastReachedAt: now, - lastError: null, - status: "reachable", - ...overrides, -}); - -describe("peerLinkHealth", () => { - it("warns only in the last days before a link expires", () => { - expect(peerLinkHealth(link({}), now)).toEqual({ kind: "reachable", expiresInDays: null }); - expect( - peerLinkHealth(link({ expiresAt: DateTime.makeUnsafe("2026-10-09T00:00:00.000Z") }), now), - ).toEqual({ kind: "reachable", expiresInDays: 3 }); - }); - - it("treats a link past its expiry as expired even if the server listed it earlier", () => { - expect( - peerLinkHealth(link({ expiresAt: DateTime.makeUnsafe("2026-10-06T11:00:00.000Z") }), now), - ).toEqual({ kind: "expired" }); - expect(peerLinkHealth(link({ status: "expired" }), now)).toEqual({ kind: "expired" }); - }); - - it("carries why an unreachable link failed last", () => { - expect( - peerLinkHealth(link({ status: "unreachable", lastError: "Box stopped answering." }), now), - ).toEqual({ kind: "unreachable", detail: "Box stopped answering." }); - }); - - it("flags a reachable link whose last call failed, such as after the peer revoked it", () => { - expect(peerLinkHealth(link({ lastError: "Box rejected the link's session." }), now)).toEqual({ - kind: "failing", - detail: "Box rejected the link's session.", - }); - }); -}); From f580fefde9a4e31cfd5ff263ea43b0d392601b31 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 13:31:14 +0000 Subject: [PATCH 118/408] fix(connections): reset pairing forms and refresh mobile link status --- .../connection/ConnectionsRouteScreen.tsx | 16 +++++---- .../connection/LinkedEnvironmentsSection.tsx | 29 ++++++++++----- .../components/auth/ConnectAgentSurface.tsx | 1 - apps/web/src/components/chat/ChatHeader.tsx | 4 +-- .../settings/LinkedEnvironmentsSettings.tsx | 36 +++++++++---------- .../src/components/settings/settingsSearch.ts | 2 -- apps/web/src/state/peerLinks.ts | 1 - packages/client-runtime/src/state/models.ts | 1 - .../client-runtime/src/state/peerLinks.ts | 4 --- 9 files changed, 47 insertions(+), 47 deletions(-) diff --git a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx index 7bb7838873b1..c6de5556da12 100644 --- a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx @@ -70,13 +70,15 @@ export function ConnectionsRouteScreen() { onSetEnabled={onSetEnvironmentEnabled} onUpdate={onUpdateEnvironment} /> - {connectedEnvironments.map((environment) => ( - - ))} + {connectedEnvironments + .filter((environment) => environment.connectionState === "connected") + .map((environment) => ( + + ))} diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx index 744ffe99afe0..66dd7dfd8f48 100644 --- a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx +++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx @@ -1,7 +1,9 @@ import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks"; +import { useFocusEffect } from "@react-navigation/native"; import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { View } from "react-native"; +import { useCallback, useState } from "react"; +import { AppState, View } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; import { useEnvironmentServerConfig } from "../../state/entities"; @@ -10,12 +12,6 @@ import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentScope } from "../../state/session"; import { SettingsSection } from "../settings/components/SettingsSection"; -/** - * The environments one connected environment links to. Listing them needs - * access:read, which a phone usually lacks, so this shows only for a session - * granted it; links are made from a desktop or `t3 environment link`, and - * revoked from the linked environment's Connections. - */ export function LinkedEnvironmentsSection(props: { readonly environmentId: EnvironmentId; readonly environmentLabel: string; @@ -26,8 +22,25 @@ export function LinkedEnvironmentsSection(props: { const links = useEnvironmentQuery( supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null, ); + const [nowMs, setNowMs] = useState(Date.now); + const hasLinks = supported && (links.data?.links.length ?? 0) > 0; + useFocusEffect( + useCallback(() => { + if (!hasLinks) return; + const updateNow = () => setNowMs(Date.now()); + updateNow(); + const timer = setInterval(updateNow, 60_000); + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") updateNow(); + }); + return () => { + clearInterval(timer); + subscription.remove(); + }; + }, [hasLinks]), + ); if (!supported || links.error || !links.data || links.data.links.length === 0) return null; - const now = DateTime.nowUnsafe(); + const now = DateTime.makeUnsafe(nowMs); return ( diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index 083f58905ce3..94d8dd4422bc 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -281,7 +281,6 @@ function ConnectAgentHeading({ ); } -/** One choice in a picker of what an outside agent, or a linked environment, may do. */ export function AccessOption({ access, selected, diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 8ed9dc899296..64881a79840d 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -43,7 +43,6 @@ interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; activeThreadId: ThreadId; activeThreadTitle: string; - /** The linked environment that started this thread, shown beside the title. */ activeThreadLinkOrigin?: string | null | undefined; isServerThread: boolean; activeProject: EnvironmentProject | null; @@ -414,8 +413,7 @@ export const ChatHeader = memo(function ChatHeader({ From {activeThreadLinkOrigin} - Started by an agent on {activeThreadLinkOrigin} through a linked environment. It can - change only threads that link started here. + Started by an agent on {activeThreadLinkOrigin} through a linked environment. ) : null} diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 4b3ed1ab2738..f3f877ba7f11 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -18,6 +18,7 @@ import { ConnectionStatusDot } from "../ConnectionStatusDot"; import { Button } from "../ui/button"; import { Dialog, + DialogClose, DialogDescription, DialogFooter, DialogHeader, @@ -36,13 +37,6 @@ import { searchableSetting } from "./settingsSearch"; const failureToast = (title: string, description: string) => toastManager.add(stackedThreadToast({ type: "error", title, description })); -/** - * Other environments this one links to, so its agents can work there. Each - * link is an outside agent session on the other environment, revoked from - * that environment's own Connections. `environmentLabel` names the linking - * environment when several are listed; only the first section is the search - * target. - */ export function LinkedEnvironmentsSettings({ environmentId, environmentLabel, @@ -169,10 +163,13 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi const formId = useId(); const accessLabelId = `${formId}-access`; const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" }); - const reset = () => { - setUrl(""); - setPairingCode(""); - setAccess("approval-required"); + const handleOpenChange = (next: boolean) => { + setOpen(next); + if (!next) { + setUrl(""); + setPairingCode(""); + setAccess("approval-required"); + } }; const submit = async () => { setBusy(true); @@ -183,8 +180,7 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi setBusy(false); if (result._tag === "Success") { toastManager.add({ type: "success", title: `Linked ${result.value.label}` }); - reset(); - setOpen(false); + handleOpenChange(false); } else if (!isAtomCommandInterrupted(result)) { failureToast("Could not link the environment", String(squashAtomCommandFailure(result))); } @@ -193,10 +189,8 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi { - // A link that finishes after a close would still be made, and would close a reopened form. if (!next && busy) return; - setOpen(next); - if (!next) reset(); + handleOpenChange(next); }} > setAccess(value as AuthMcpClientAccess)} > @@ -262,16 +257,17 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi ))}

- An agent here never gets more there than its own mode here either. Threads it starts - there cannot change that environment's own threads, projects or settings. + An agent never gets more access there than its own mode here. Below full access, it + can change only threads this link started, not that environment's own threads, + projects or settings.

- +
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 5262b5591695..24998eee7e8a 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -32,8 +32,10 @@ import { isProviderNativeSubagentThread, NodeId, type EnvironmentId, + type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, type OrchestrationV2ThreadShell, + type ServerProvider, type ThreadId, } from "@t3tools/contracts"; import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming"; @@ -60,7 +62,7 @@ import { useThreadProjection, useThreadRelationshipShells, } from "../../state/entities"; -import { useEnvironmentProviders } from "../../state/environments"; +import { useEnvironment, useEnvironmentProviders } from "../../state/environments"; import { threadEnvironment } from "../../state/threads"; import { orchestrationEnvironment } from "../../state/orchestration"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -207,6 +209,74 @@ function currentSubagent( }; } +/** + * A task delegated to a linked environment. It has no thread here, so it opens + * the thread there, when this client is connected to that environment. + */ +function RemoteSubagentRow(props: { + readonly agent: OrchestrationV2Subagent & { + readonly remoteChild: OrchestrationV2RemoteTaskChild; + }; + readonly provider: ServerProvider | undefined; +}) { + const navigate = useNavigate(); + const environment = useEnvironment(props.agent.remoteChild.environmentId); + const { remoteChild } = props.agent; + const status = props.agent.status; + const failed = status === "failed"; + const title = relationshipThreadTitle({ + title: props.agent.title ?? "Subagent", + isSubagent: true, + }); + return ( +
  • + + + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams( + scopeThreadRef(remoteChild.environmentId, remoteChild.threadId), + ), + }) + } + /> + } + > + + + + {title} + + + + on {remoteChild.label} · {threadRelationshipStatusLabel(status)} + + + + {environment === null + ? `Runs on ${remoteChild.label}. Connect to it to open the thread there.` + : `Open on ${remoteChild.label}`} + + +
  • + ); +} + export function ThreadRelationshipsPanel(props: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -323,12 +393,17 @@ export function ThreadRelationshipsPanel(props: { { id: "active", label: null, rows: active, expanded: true }, { id: "previous", label: "Previous agents", rows: previous, expanded: false }, ]; + // Tasks running in a linked environment have no thread here; they get their own rows. + const remoteSubagents = (projection?.subagents ?? []).filter( + (agent): agent is OrchestrationV2Subagent & { remoteChild: OrchestrationV2RemoteTaskChild } => + agent.remoteChild !== undefined, + ); const runningCount = (projection?.subagents.filter( (agent) => agent.childThreadId === null && agent.status === "running", ).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length; - if (relationshipRows.length === 0 && runningCount === 0) { + if (relationshipRows.length === 0 && runningCount === 0 && remoteSubagents.length === 0) { return null; } @@ -689,6 +764,20 @@ export function ThreadRelationshipsPanel(props: { } ))} + {remoteSubagents.length > 0 ? ( + {}}> + {remoteSubagents.map((agent) => ( + entry.instanceId === agent.providerInstanceId)} + /> + ))} + + ) : null} ); } diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 06e6f8fc3b3a..a1bc385daceb 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -3,6 +3,9 @@ import { AgentElapsed } from "./AgentElapsed"; import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime"; import type { ReactNode } from "react"; import { useThreadShell, useProject } from "../../state/entities"; +import { useEnvironment } from "../../state/environments"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { useNavigate } from "@tanstack/react-router"; import { SubagentTooltipContent } from "./SubagentTooltipContent"; import { useAtomValue } from "@effect/atom-react"; import { scopeThreadRef, scopeProjectRef } from "@t3tools/client-runtime/environment"; @@ -21,6 +24,7 @@ import { ProviderDriverKind, type OrchestrationV2Notification, type OrchestrationV2TurnItem, + type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, type ProviderInstanceId, type ServerProvider, @@ -204,6 +208,7 @@ export function V2LifecycleRow(props: { startedAt={item.startedAt} completedAt={item.completedAt} threadId={item.childThreadId} + remote={item.remoteChild} onOpenThread={props.onOpenThread} /> ); @@ -408,6 +413,8 @@ function SubagentTimelineLink(props: { readonly startedAt: DateTime.Utc | null; readonly completedAt: DateTime.Utc | null; readonly threadId: ThreadId | null; + /** The thread in a linked environment that runs this task, when it runs there. */ + readonly remote?: OrchestrationV2RemoteTaskChild | undefined; readonly onOpenThread: (threadId: ThreadId) => void; readonly event?: { readonly status: OrchestrationV2TurnItem["status"] | null; @@ -419,7 +426,21 @@ function SubagentTimelineLink(props: { environmentThreadDetails.threadAtom(props.parentRef), (thread) => thread?.projection.subagents.find((agent) => agent.id === props.subagentId) ?? null, ); + const remote = props.remote ?? agent?.remoteChild; + const remoteEnvironment = useEnvironment(remote?.environmentId ?? null); + const navigate = useNavigate(); const threadId = props.threadId; + // A task in a linked environment opens there, if this client is connected to it. + const open = + threadId !== null + ? () => props.onOpenThread(threadId) + : remote !== undefined && remoteEnvironment !== null + ? () => + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(remote.environmentId, remote.threadId)), + }) + : null; const liveStatus = agent?.status ?? props.status; const status = props.event ? props.event.status : liveStatus; const statusLabel = props.event?.label ?? subagentStatusVisual(liveStatus).label; @@ -448,6 +469,9 @@ function SubagentTimelineLink(props: { {props.title} + {remote !== undefined ? ( + on {remote.label} + ) : null} {detail !== null && (props.event !== undefined || status !== "completed") ? ( {props.event ? props.event.timestamp : } - {threadId !== null ? ( + {open !== null ? ( {content}
    @@ -502,7 +526,7 @@ function SubagentTimelineLink(props: { data-v2-item-type="subagent" aria-label={`Open ${props.title}`} aria-description={statusLabel} - onClick={() => props.onOpenThread(threadId)} + onClick={open} className={cn( className, "cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70", diff --git a/docs/internals/remote.md b/docs/internals/remote.md index bdeabb693da8..4d555ff7dee4 100644 --- a/docs/internals/remote.md +++ b/docs/internals/remote.md @@ -108,6 +108,15 @@ shared access declarations, not tool by tool: Reads are not fenced, and a client's own `thread.create` can never carry `linkOrigin`. +**A delegated task can run in a linked environment.** Its child is then an +ordinary thread there, so the parent here records the task without a child +thread of its own (`remoteChild` instead of `childThreadId`). A follower in +[`RemoteDelegation`](../../apps/server/src/peer/RemoteDelegation.ts) waits on +that thread and completes the task with `delegated_task.remote.complete`. That +internal command reuses the parent half of a local finalize, so the parent +wakes the same way. Open remote tasks are followed again at startup, which is +also what keeps restart recovery from treating them as abandoned provider work. + The link is routing, not isolation: an agent the link starts runs as the receiving environment's user. **A full-access link is therefore not fenced**: its agents can already do anything that user can, so the fence would only stop diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index ce0934b6762f..00096ae4169f 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -268,6 +268,13 @@ it. From a terminal, use removes it here. - Links last 30 days. Link again with a new pairing code to renew one. +An agent can also hand a task to a linked machine with `delegate_task`: it runs +there as an ordinary thread, in the project with the same repository (or the +one `target.projectId` names), and this thread wakes with its result when it +ends, as for any delegated task. It keeps following the task across restarts. +If the other machine revokes the link, or the link is removed here, the task +fails with that reason. + ## Manage or revoke access On the host, **Settings → Connections** lets authorized administrators create diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 45f29fb4e49f..482c0a287a16 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -101,6 +101,8 @@ export interface EnvironmentThreadShell { readonly lineage: OrchestrationV2ThreadShell["lineage"]; readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"]; readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null; + /** The thread in a linked environment that delegated this one, if one did. */ + readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null; readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; readonly latestRun: ThreadRunSummary | null; readonly runtime: ThreadRuntimeSummary | null; @@ -248,6 +250,7 @@ export function presentThreadShell( lineage: thread.lineage, forkedFrom: thread.forkedFrom, linkOrigin: thread.linkOrigin ?? null, + delegatedFrom: thread.delegatedFrom ?? null, activeProviderThreadId: thread.activeProviderThreadId, latestRun, runtime, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 197626f67903..8f69b6b39bcd 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -15,6 +15,7 @@ import { EventId, IsoDateTime, MessageId, + EnvironmentId, NodeId, ForwardCompatibleUnion, ForwardCompatibleUnionArray, @@ -117,6 +118,17 @@ export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type; export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) => origin.access !== "full-access"; +/** + * The thread in a linked environment that delegated this one, when it did: + * this thread is that parent's subagent, run here instead of there. + */ +export const OrchestrationV2DelegatedFrom = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + title: Schema.String, +}); +export type OrchestrationV2DelegatedFrom = typeof OrchestrationV2DelegatedFrom.Type; + export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]); export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type; @@ -410,6 +422,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ activeProviderThreadId: Schema.NullOr(ProviderThreadId), historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), lineage: OrchestrationV2AppThreadLineage, forkedFrom: Schema.NullOr( Schema.Union([ @@ -720,6 +733,28 @@ export const OrchestrationV2SubagentWorkflow = Schema.Struct({ }); export type OrchestrationV2SubagentWorkflow = typeof OrchestrationV2SubagentWorkflow.Type; +/** + * Where an app-owned task runs when it runs in a linked environment instead + * of in a child thread here: that environment and the ordinary thread it runs + * as there. Such a task has no `childThreadId`. + */ +export const OrchestrationV2RemoteTaskChild = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + label: Schema.String, + /** The run there that carries the task; absent on tasks recorded before it was kept. */ + runId: Schema.optional(RunId), + /** + * Nothing is left to stop there: a stop from here reached the thread there, + * the other side refused it for good, or the thread or its link is gone. A + * task's run that ended there by itself also sets it, unless the task here + * was cancelled or stopped, which still owes a stop for whatever runs on the + * thread there now. Its follower keeps sending that stop, across restarts. + */ + stoppedThere: Schema.optional(Schema.Boolean), +}); +export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type; + export const OrchestrationV2Subagent = Schema.Struct({ id: NodeId, threadId: ThreadId, @@ -731,6 +766,7 @@ export const OrchestrationV2Subagent = Schema.Struct({ providerInstanceId: ProviderInstanceId, providerThreadId: Schema.NullOr(ProviderThreadId), childThreadId: Schema.NullOr(ThreadId), + remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild), nativeTaskRef: Schema.NullOr(OrchestrationV2ProviderRef), prompt: Schema.String, title: Schema.NullOr(Schema.String), @@ -1549,6 +1585,7 @@ export const OrchestrationV2TurnItem = Schema.Union([ driver: ProviderDriverKind, providerInstanceId: ProviderInstanceId, childThreadId: Schema.NullOr(ThreadId), + remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild), prompt: Schema.String, progress: Schema.optional(Schema.String), result: Schema.NullOr(Schema.String), @@ -1849,6 +1886,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ activeProviderThreadId: Schema.NullOr(ProviderThreadId), historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), latestRunId: Schema.NullOr(RunId), latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -2312,6 +2350,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ driver: ProviderDriverKind, providerInstanceId: ProviderInstanceId, childThreadId: Schema.NullOr(ThreadId), + remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild), prompt: Schema.String, progress: Schema.optional(Schema.String), result: Schema.NullOr(Schema.String), @@ -2611,6 +2650,8 @@ export const OrchestrationV2Command = Schema.Union([ worktreePath: Schema.NullOr(TrimmedNonEmptyString), /** Only the server sets this; a client's thread.create never carries one. */ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */ + delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), importedNativeThread: Schema.optional( Schema.Struct({ ref: Schema.Struct({ @@ -3063,6 +3104,46 @@ const OrchestrationV2InternalCommand = Schema.Union([ }), ), }), + /** + * Records a delegated task that runs in a linked environment: the task, its + * node and its turn item on the parent, as `delegated_task.request` does, + * without a child thread here. `remoteChild` is the thread already launched + * there. The ids derive from `commandId`, so a retry records nothing new. + */ + Schema.Struct({ + type: Schema.Literal("delegated_task.remote.request"), + commandId: CommandId, + parentThreadId: ThreadId, + parentRunId: RunId, + parentNodeId: NodeId, + task: TrimmedNonEmptyString, + title: Schema.optional(TrimmedNonEmptyString), + driver: ProviderDriverKind, + modelSelection: ModelSelection, + remoteChild: OrchestrationV2RemoteTaskChild, + completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])), + }), + /** + * Completes a delegated task that ran in a linked environment, with what its + * thread there ended as. The parent wakes exactly as for a child here. A + * task that already has a result keeps it; `stoppedThere` is still recorded. + */ + Schema.Struct({ + type: Schema.Literal("delegated_task.remote.complete"), + commandId: CommandId, + parentThreadId: ThreadId, + taskId: NodeId, + status: Schema.Literals(["completed", "failed", "cancelled", "interrupted"]), + result: Schema.String, + /** + * What this report says about stopping there: `ran-out` when the task's + * run ended there by itself, `stopped` when a stop from here reached it. + * Either sets `remoteChild.stoppedThere` on a task this report completes; + * on a task already cancelled or stopped here, only `stopped` does, since + * a run that ended by itself leaves the stop owed for what may follow it. + */ + stoppedThere: Schema.optional(Schema.Literals(["ran-out", "stopped"])), + }), Schema.Struct({ type: Schema.Literal("checkpoint.rollback.fail"), commandId: CommandId, diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index af88860f28ed..c03920ac6799 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -117,6 +117,18 @@ export const OrchestratorMcpTarget = Schema.Struct({ "Model options from orchestrator_capabilities. For the same provider instance and model, overrides individual inherited values; [] or {} clears them. Claude: {effort: 'max', fastMode: true}; Codex: {reasoningEffort: 'max', serviceTier: 'priority'}. Only use options advertised by the selected model.", }), ), + environmentId: Schema.optional( + EnvironmentId.annotate({ + description: + "Run the task in a linked environment (t3_environment_links). It uses this thread's provider and model unless providerInstanceId and model name others from orchestrator_capabilities with this environmentId.", + }), + ), + projectId: Schema.optional( + ProjectId.annotate({ + description: + "With environmentId: that environment's project to run in. Omit to use the one with the same repository as this thread's project.", + }), + ), }); export type OrchestratorMcpTarget = typeof OrchestratorMcpTarget.Type; @@ -195,7 +207,12 @@ export type OrchestratorMcpDelegateTaskInput = typeof OrchestratorMcpDelegateTas export const OrchestratorMcpDelegateTaskResult = Schema.Struct({ taskId: NodeId, - childThreadId: ThreadId, + /** Null for a task that runs in a linked environment; see `remoteChild`. */ + childThreadId: Schema.NullOr(ThreadId), + /** The linked environment and thread a remote task runs as. */ + remoteChild: Schema.optional( + Schema.Struct({ environmentId: EnvironmentId, threadId: ThreadId, label: Schema.String }), + ), childRunId: Schema.NullOr(RunId), childNodeId: NodeId, status: OrchestratorMcpDelegatedTaskStatus, From 895fcfb24ef35523fd6e317029b9e83dfb6f4f8e Mon Sep 17 00:00:00 2001 From: Lenori <122464369+Lenoridev@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:41:43 +0200 Subject: [PATCH 120/408] fix(server): report the failed remote run's provider error Read failed-run activity and prefer that run's error over an earlier assistant reply. Keep successful replies unchanged and retrieve long errors in full without taking diagnostics from a later run. Add failed-run, pagination, run-isolation and successful-recovery regressions for the existing review on pingdotgg/t3code#16719. Implemented with GPT-6.1-Sol through Codex in T3 Code on behalf of Lenoridev. --- apps/server/src/peer/RemoteDelegation.test.ts | 167 ++++++++++++++++-- apps/server/src/peer/RemoteDelegation.ts | 22 ++- 2 files changed, 172 insertions(+), 17 deletions(-) diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 74395c88dc6b..87008e823904 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -91,7 +91,9 @@ interface BoxThread { /** The first message the thread there was launched with. */ readonly message: Ref.Ref; readonly status: Ref.Ref; - readonly reply: Ref.Ref; + readonly reply: Ref.Ref; + readonly error: Ref.Ref; + readonly laterError: Ref.Ref; /** A later run's reply, after the task's own, as a follow-up message would leave. */ readonly laterReply: Ref.Ref; /** The run each wait asked for, in order. */ @@ -122,7 +124,9 @@ const makeBoxThread = Effect.gen(function* () { launchedWith: yield* Ref.make(null), message: yield* Ref.make(null), status: yield* Ref.make("running"), - reply: yield* Ref.make("Working…"), + reply: yield* Ref.make("Working…"), + error: yield* Ref.make(null), + laterError: yield* Ref.make(null), laterReply: yield* Ref.make(null), waitedFor: yield* Ref.make>([]), gone: yield* Ref.make(false), @@ -260,19 +264,55 @@ const boxToolkitLayer = (thread: BoxThread) => { } const reply = yield* Ref.get(thread.reply); const later = yield* Ref.get(thread.laterReply); - // One assistant message per page, so a read has to page to find the task's. + const error = yield* Ref.get(thread.error); + const laterError = yield* Ref.get(thread.laterError); + // One item per page, with errors available only in the activity view. const replies = [ - { id: TurnItemId.make("item:reply"), runId, text: reply }, + ...(reply === null + ? [] + : [ + { + id: TurnItemId.make("item:reply"), + runId, + text: reply, + type: "assistant_message", + }, + ]), + ...(error === null + ? [] + : [{ id: TurnItemId.make("item:error"), runId, text: error, type: "error" }]), ...(later === null ? [] - : [{ id: TurnItemId.make("item:later-reply"), runId: boxLaterRunId, text: later }]), + : [ + { + id: TurnItemId.make("item:later-reply"), + runId: boxLaterRunId, + text: later, + type: "assistant_message", + }, + ]), + ...(laterError === null + ? [] + : [ + { + id: TurnItemId.make("item:later-error"), + runId: boxLaterRunId, + text: laterError, + type: "error", + }, + ]), ].map((entry, position) => ({ ...entry, position })); - const matching = + const visible = options.itemId === undefined - ? replies.filter((entry) => entry.position > (options.afterPosition ?? -1)).slice(0, 1) + ? replies.filter( + (entry) => options.view === "activity" || entry.type === "assistant_message", + ) : replies.filter((entry) => entry.id === options.itemId); + const matching = visible + .filter((entry) => entry.position > (options.afterPosition ?? -1)) + .slice(0, 1); return { - items: matching.map(({ id, runId: itemRunId, text, position }) => ({ + items: matching.map(({ id, runId: itemRunId, text, position, type }) => ({ position, visibility: "local" as const, sourceThreadId: threadId, @@ -292,17 +332,21 @@ const boxToolkitLayer = (thread: BoxThread) => { startedAt: DateTime.makeUnsafe(0), completedAt: DateTime.makeUnsafe(0), updatedAt: DateTime.makeUnsafe(0), - type: "assistant_message" as const, - messageId: MessageId.make(`message:${id}`), - text, - streaming: false, + ...(type === "error" + ? { type, failure: { message: text } } + : { + type: "assistant_message" as const, + messageId: MessageId.make(`message:${id}`), + text, + streaming: false, + }), } as never, })), totalItems: replies.length, hasMore: options.itemId === undefined && matching.length > 0 && - matching.at(-1)!.position < replies.length - 1, + visible.some((entry) => entry.position > matching.at(-1)!.position), }; }), interruptThread: (input) => @@ -947,6 +991,103 @@ it.effect("the same key from another provider session is another task", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect.each([null, "Working before the provider failed."])( + "reports the failed remote run's error instead of its earlier reply (%s)", + (reply) => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, reply); + const error = "Provider failed: authentication expired on the destination."; + yield* Ref.set(thread.error, error); + yield* Ref.set(thread.status, "failed"); + yield* Deferred.succeed(thread.finished, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "failed", + result: error, + }); + const status = yield* a.call("task_status", { taskId: delegated.taskId }); + expect(status.structuredContent).toMatchObject({ + status: "failed", + summary: error, + latestTerminalSummary: error, + }); + const offered = yield* SubscriptionRef.changes(offers).pipe( + Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)), + Stream.runHead, + ); + expect(Option.isSome(offered)).toBe(true); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect.each([false, true])( + "ignores later-run errors and reads the failed run's full error (ownError=%s)", + (ownError) => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, null); + const error = `Provider failed: ${"detail ".repeat(10_000)}end of error.`; + if (ownError) yield* Ref.set(thread.error, error); + yield* Ref.set(thread.laterReply, "A later user run answered."); + yield* Ref.set(thread.laterError, "Another run's provider error."); + yield* Ref.set(thread.status, "failed"); + yield* Deferred.succeed(thread.finished, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "failed", + result: ownError + ? error + : "(The thread in the linked environment ended without a reply.)", + }); + expect(yield* Ref.get(thread.waitedFor)).toEqual([boxRunId]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("keeps a successful remote reply despite an error item in the run's activity", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "Recovered and completed the task."); + yield* Ref.set(thread.error, "A recoverable tool error."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "completed", + result: "Recovered and completed the task.", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("fails the task when its thread there is gone, or the link here is", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 4edf6d055dae..3fd6f707503c 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -405,21 +405,23 @@ const make = Effect.gen(function* () { /** * The last reply `runId` gave on the task's thread there, which is its - * result, read whole however long it is. A read only pages forward, so - * it pages through the thread. + * result, read whole however long it is. A failed run prefers its error + * from the activity view over an earlier reply, without taking another run's. */ const lastReply = ( scope: ThreadScope, remote: OrchestrationV2RemoteTaskChild, runId: RunId | null, + failed = false, ) => Effect.gen(function* () { let reply: OrchestratorMcpThreadTimelineItem | undefined; + let error: OrchestratorMcpThreadTimelineItem | undefined; let afterPosition: number | undefined; while (true) { const read = yield* forwarding.readThread(scope, remote.environmentId, { threadId: remote.threadId, - view: "messages", + view: failed ? "activity" : "messages", limit: 100, ...(afterPosition === undefined ? {} : { afterPosition }), }); @@ -427,9 +429,16 @@ const make = Effect.gen(function* () { read.items.findLast( (item) => item.type === "assistant_message" && (runId === null || item.runId === runId), ) ?? reply; + if (failed) { + error = + read.items.findLast( + (item) => item.type === "error" && (runId === null || item.runId === runId), + ) ?? error; + } if (!read.hasMore || read.nextPosition === null) break; afterPosition = read.nextPosition; } + reply = error ?? reply; if (reply === undefined) return undefined; let text = reply.text ?? ""; let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null; @@ -571,7 +580,12 @@ const make = Effect.gen(function* () { return yield* settled(parentThreadId, taskId); } if (!isTerminal(waited.status)) return false; - const result = yield* lastReply(scope, remote, remote.runId ?? waited.runId); + const result = yield* lastReply( + scope, + remote, + remote.runId ?? waited.runId, + waited.status === "failed", + ); yield* complete( parentThreadId, taskId, From a9914de7adad9c15d809ebc901f196283a05e062 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:23:57 -0700 Subject: [PATCH 121/408] fix(server): a remote task waits for its thread's delegated work When the task's run on the linked environment ended, the follower completed the task with that run's reply, even while the thread there still waited on its own subagents, background tasks or a completion delivery that would wake it for the real answer. A local task waits for that work and takes its result from the run that answered after it. t3_thread_wait takes an optional untilDelegatedWorkSettled. With it, the wait also blocks until delegatedTaskProgress reports result_available for the thread, waking on task, provider-thread and run updates, and reports that result run as resultRun. The follower passes it and reads the result from resultRun. Both fields are optional: an older peer ignores the input and answers as before, and the follower then falls back to the launched run. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 6 ++ .../ThreadManagementService.test.ts | 88 +++++++++++++++++++ .../ThreadManagementService.ts | 84 +++++++++++++----- apps/server/src/peer/PeerForwarding.ts | 9 +- apps/server/src/peer/RemoteDelegation.test.ts | 64 ++++++++++++++ apps/server/src/peer/RemoteDelegation.ts | 14 ++- packages/contracts/src/orchestratorMcp.ts | 8 ++ 7 files changed, 248 insertions(+), 25 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 9485d1f496bb..c1f515df3ca9 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2936,6 +2936,7 @@ const make = Effect.gen(function* () { MAX_WAIT_TIMEOUT_MS, Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), ), + ...(input.untilDelegatedWorkSettled === true ? { untilDelegatedWorkSettled: true } : {}), }) .pipe(Effect.mapError(threadManagementFailure)); return { @@ -2943,6 +2944,11 @@ const make = Effect.gen(function* () { runId: result.run?.id ?? null, status: result.run === null ? "idle" : runOutcome(result.run), timedOut: result.timedOut, + ...(result.resultRun === undefined + ? {} + : { + resultRun: { runId: result.resultRun.id, status: runOutcome(result.resultRun) }, + }), } satisfies OrchestratorMcpThreadWaitResult; }), interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index f2a533afb293..52e4c1d36cdd 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -290,6 +290,94 @@ it.effect("waitForThread follows a restart continuation instead of the cut run", }), ); +it.effect("waitForThread can wait past an ended run for the thread's delegated work", () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:wait-delegated"); + const threadId = ThreadId.make("thread:thread-management:wait-delegated"); + const runId = RunId.make("run:thread-management:wait-delegated"); + const wakeRunId = RunId.make("run:thread-management:wait-delegated:wake"); + const subscribed = yield* Deferred.make(); + const events = yield* Queue.unbounded(); + const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000); + const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"], end: number) => + ({ + id, + ordinal, + status, + startedAt: at(end - 1), + completedAt: status === "running" ? null : at(end), + }) as unknown as OrchestrationV2Run; + // The run ended, but a task it delegated still runs and will wake the thread. + let runs = [run(runId, 1, "completed", 1)]; + let subagents = [{ status: "running" }]; + const stored = (sequence: number, event: object) => + ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + delegatedTaskResultPending: () => Effect.succeed(false), + streamStoredEventsFrom: (input) => + input?.eventType === "subagent.updated" + ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(events)), + ) + : Stream.never, + getThreadRecords: () => + Effect.sync( + () => + ({ + thread: { id: threadId, projectId, deletedAt: null }, + runs, + messages: [], + subagents, + providerThreads: [], + }) as unknown as OrchestrationV2ThreadProjection, + ), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + // Without the option, the ended run is the answer, as before. + expect( + yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }), + ).toMatchObject({ timedOut: false, run: { id: runId } }); + expect( + yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }), + ).not.toHaveProperty("resultRun"); + + const fiber = yield* service + .waitForThread({ + projectId, + threadId, + runId, + timeoutMs: 60 * 60 * 1_000, + untilDelegatedWorkSettled: true, + }) + .pipe(Effect.forkChild); + // A wait that returns early fails below instead of hanging here. + yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber)); + // The task finishes; its delivery wakes the thread, whose next run answers. + subagents = [{ status: "completed" }]; + runs = [...runs, run(wakeRunId, 2, "completed", 3)]; + yield* Queue.offer(events, stored(1, { type: "subagent.updated", payload: {} })); + const result = yield* Fiber.join(fiber); + + expect(result).toMatchObject({ + timedOut: false, + run: { id: runId, status: "completed" }, + resultRun: { id: wakeRunId, status: "completed" }, + }); + }), +); + it.effect("waitForThread returns the cut run once its continuation is declined", () => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-declined"); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 0ef249632563..60bb6c722625 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -35,6 +35,7 @@ import { ThreadId, type TurnItemId, } from "@t3tools/contracts"; +import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -156,12 +157,20 @@ export interface ThreadManagementWaitInput { readonly threadId: ThreadId; readonly runId?: RunId; readonly timeoutMs: number; + /** + * Also wait until the thread's own delegated work settles: an ended run + * still owes the thread's answer while a child, a background task or a + * completion delivery will wake it again, as a delegated task's result does. + */ + readonly untilDelegatedWorkSettled?: boolean; } export interface ThreadManagementWaitResult { readonly threadId: ThreadId; readonly run: OrchestrationV2Run | null; readonly timedOut: boolean; + /** With `untilDelegatedWorkSettled`, once settled: the run with the thread's final answer. */ + readonly resultRun?: OrchestrationV2Run; } export interface ThreadManagementInterruptInput { @@ -882,29 +891,65 @@ const make = Effect.gen(function* () { isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run)); return { run, pending, settled: isTerminalRunStatus(run.status) && !pending }; }); - const initial = yield* outcome(target.runs); - if (initial.settled) { - return { threadId: input.threadId, run: initial.run, timedOut: false }; - } + const untilDelegatedWorkSettled = input.untilDelegatedWorkSettled === true; + const delegatedWorkResult = Effect.gen(function* () { + const records = yield* getProjectThreadRecords( + input, + ["runs", "messages", "subagents", "providerThreads"], + { messageRoles: ["user"] }, + ); + const progress = delegatedTaskProgress(records); + if (progress.state !== "result_available") return undefined; + const pending = yield* orchestrator + .delegatedTaskResultPending(input.threadId) + .pipe(Effect.mapError(loadError)); + return pending ? undefined : progress.resultRun; + }); + const evaluate = (runs: ReadonlyArray) => + Effect.gen(function* () { + const current = yield* outcome(runs); + if (!current.settled || !untilDelegatedWorkSettled) { + return { ...current, resultRun: undefined }; + } + const resultRun = yield* delegatedWorkResult; + return { ...current, settled: resultRun !== undefined, resultRun }; + }); + const settledResult = (current: Effect.Success>) => ({ + threadId: input.threadId, + run: current.run, + timedOut: !current.settled, + ...(current.resultRun === undefined ? {} : { resultRun: current.resultRun }), + }); + const initial = yield* evaluate(target.runs); + if (initial.settled) return settledResult(initial); // A declined continuation records no event, so its effect settling wakes // the wait too. const wait = Stream.merge( - Stream.merge( - orchestrator.streamStoredEventsFrom({ - threadId: input.threadId, - afterSequence, - eventType: "run.updated", - }), - orchestrator.streamStoredEventsFrom({ - threadId: input.threadId, - afterSequence, - eventType: "thread.deleted", - }), + Stream.mergeAll( + ( + [ + "run.updated", + "thread.deleted", + // What delegated work reads besides runs: tasks and their + // deliveries, and a provider thread's background tasks. + ...(untilDelegatedWorkSettled + ? (["subagent.updated", "provider-thread.updated"] as const) + : []), + ] as const + ).map((eventType) => + orchestrator.streamStoredEventsFrom({ + threadId: input.threadId, + afterSequence, + eventType, + }), + ), + { concurrency: "unbounded" }, ).pipe( Stream.mapError(loadError), Stream.filter( (stored) => + untilDelegatedWorkSettled || stored.event.type !== "run.updated" || stored.event.payload.id === selectedRun.id || stored.event.payload.restartContinuationOfRunId !== undefined, @@ -916,7 +961,7 @@ const make = Effect.gen(function* () { ).pipe( Stream.mapEffect(() => getProjectThreadRecords(input, ["runs"]).pipe( - Effect.flatMap((current) => outcome(current.runs)), + Effect.flatMap((current) => evaluate(current.runs)), ), ), Stream.filter((current) => current.settled), @@ -924,14 +969,11 @@ const make = Effect.gen(function* () { Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))), ); const waited = Option.flatten(yield* wait); - if (Option.isSome(waited)) { - return { threadId: input.threadId, run: waited.value.run, timedOut: false }; - } + if (Option.isSome(waited)) return settledResult(waited.value); // The run may have reached a terminal status while the timeout was // winning the race; the final projection read decides what actually // happened, so only a still-active run counts as timed out. - const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs); - return { threadId: input.threadId, run: final.run, timedOut: !final.settled }; + return settledResult(yield* evaluate((yield* getProjectThreadRecords(input, ["runs"])).runs)); }); const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn( diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index aeed2dba84e3..2121f2c7eabc 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -189,7 +189,14 @@ const make = Effect.gen(function* () { OrchestratorMcpThreadWaitInput, OrchestratorMcpThreadWaitResult, environmentId, - { threadId: input.threadId, ...(runId === undefined ? {} : { runId }), timeoutMs: chunk }, + { + threadId: input.threadId, + ...(runId === undefined ? {} : { runId }), + timeoutMs: chunk, + ...(input.untilDelegatedWorkSettled === undefined + ? {} + : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }), + }, ); remaining -= chunk; if (!result.timedOut || remaining <= 0) return result; diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 87008e823904..1c101c52a30d 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -98,6 +98,12 @@ interface BoxThread { readonly laterReply: Ref.Ref; /** The run each wait asked for, in order. */ readonly waitedFor: Ref.Ref>; + /** The thread's run ends with a task of its own still running, whose result wakes it again. */ + readonly nested: Ref.Ref; + /** Completed once a wait there blocks on that task. */ + readonly nestedWaiting: Deferred.Deferred; + /** That task settled and the run it woke answered, with `laterReply`. */ + readonly nestedSettled: Deferred.Deferred; /** Waiting there fails with this, as a thread deleted there does. */ readonly gone: Ref.Ref; readonly interrupted: Ref.Ref; @@ -129,6 +135,9 @@ const makeBoxThread = Effect.gen(function* () { laterError: yield* Ref.make(null), laterReply: yield* Ref.make(null), waitedFor: yield* Ref.make>([]), + nested: yield* Ref.make(false), + nestedWaiting: yield* Deferred.make(), + nestedSettled: yield* Deferred.make(), gone: yield* Ref.make(false), interrupted: yield* Ref.make(0), stops: yield* Ref.make>([]), @@ -245,6 +254,25 @@ const boxToolkitLayer = (thread: BoxThread) => { const done = yield* Deferred.await(thread.finished).pipe( Effect.timeoutOption(input.timeoutMs), ); + // Only a waiter that asks waits past the run for the thread's own task. + if ( + Option.isSome(done) && + input.untilDelegatedWorkSettled === true && + (yield* Ref.get(thread.nested)) + ) { + yield* Deferred.succeed(thread.nestedWaiting, undefined); + const settled = yield* Deferred.await(thread.nestedSettled).pipe( + Effect.timeoutOption(input.timeoutMs), + ); + return { + threadId: input.threadId, + run: { id: runId, status: yield* Ref.get(thread.status) } as OrchestrationV2Run, + timedOut: Option.isNone(settled), + ...(Option.isSome(settled) + ? { resultRun: { id: boxLaterRunId, status: "completed" } as OrchestrationV2Run } + : {}), + }; + } // Unpinned, a wait reports the latest run: a later one once there is one. const later = input.runId === undefined && (yield* Ref.get(thread.laterReply)) !== null; return { @@ -956,6 +984,42 @@ it.effect("a task's result is its own run's whole last reply, not a later run's" ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("a task whose thread there waits on its own task ends with the answer after it", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + + // The task's run there ends after delegating a review of its own. + yield* Ref.set(thread.nested, true); + yield* Ref.set(thread.reply, "Started a review; I will answer when it reports."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + const first = yield* Effect.raceFirst( + Deferred.await(thread.nestedWaiting).pipe(Effect.as("waiting there" as const)), + taskResult(a, delegated.taskId).pipe(Effect.as("completed here" as const)), + ); + expect(first).toBe("waiting there"); + + // The review reports and wakes the thread there, whose next run answers. + yield* Ref.set(thread.laterReply, "The review found two issues; both are fixed."); + yield* Deferred.succeed(thread.nestedSettled, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "completed", + result: "The review found two issues; both are fixed.", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("the same key from another provider session is another task", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 3fd6f707503c..65940ed78bbd 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -561,6 +561,10 @@ const make = Effect.gen(function* () { threadId: remote.threadId, ...(remote.runId === undefined ? {} : { runId: remote.runId }), timeoutMs: FOLLOW_WAIT_MS, + // A thread there whose run ended may still be waiting on its own + // tasks to wake it for the answer, which a task here waits for too. + // An older peer ignores this and reports the run alone. + untilDelegatedWorkSettled: true, }) .pipe(Effect.raceFirst(endedHere)); // The next look reads the result and stops it there. @@ -580,16 +584,20 @@ const make = Effect.gen(function* () { return yield* settled(parentThreadId, taskId); } if (!isTerminal(waited.status)) return false; + const resultRun = waited.resultRun ?? { + runId: remote.runId ?? waited.runId, + status: waited.status, + }; const result = yield* lastReply( scope, remote, - remote.runId ?? waited.runId, - waited.status === "failed", + resultRun.runId, + resultRun.status === "failed", ); yield* complete( parentThreadId, taskId, - terminalStatus(waited.status), + terminalStatus(resultRun.status), result ?? noReply, "ran-out", ); diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index c03920ac6799..838fd6674aa2 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -528,6 +528,12 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({ threadId: ThreadId, runId: Schema.optional(RunId), timeoutMs: Schema.optional(Schema.Finite), + untilDelegatedWorkSettled: Schema.optional( + Schema.Boolean.annotate({ + description: + "Also wait until the thread's own delegated tasks, background tasks and their completion deliveries settle, as a delegated task's result does. resultRun then names the run with the thread's final answer.", + }), + ), }); export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type; @@ -536,6 +542,8 @@ export const OrchestratorMcpThreadWaitResult = Schema.Struct({ runId: Schema.NullOr(RunId), status: OrchestratorMcpThreadStatus, timedOut: Schema.Boolean, + /** With untilDelegatedWorkSettled, once settled: the run whose reply is the thread's result. */ + resultRun: Schema.optional(Schema.Struct({ runId: RunId, status: OrchestrationV2RunStatus })), }); export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type; From efac76814215611d6522ca09efbfba29e34ad8b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:26:53 -0700 Subject: [PATCH 122/408] fix(server): stopping a parent stops a finished remote task's thread there Stop on a parent skipped a remote task that already had its result, so follow-up work on its thread in the linked environment (a message sent there with t3_thread_send, or a run that started after the result) kept running. A local child is stopped on every Stop, result or not, and cancelling a finished remote task already stops its thread there. Stop now records the owed stop with an internal delegated_task.remote.stop command: it sets remoteChild.stoppedThere to false and counts the stop, leaving the status, result and completion delivery alone. The follower, restarted from the live event tail or by the startup scan, sends that stop under a key per count and records it as "stopped"; a "ran-out" report never clears it. One follower runs per task, and a request while it runs makes it look once more. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 67 ++++++++- .../src/orchestration-v2/ProjectionStore.ts | 4 +- .../ThreadManagementService.ts | 36 +++-- apps/server/src/peer/RemoteDelegation.test.ts | 131 ++++++++++++++++++ apps/server/src/peer/RemoteDelegation.ts | 75 ++++++++-- packages/contracts/src/orchestrationV2.ts | 19 +++ 6 files changed, 310 insertions(+), 22 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0252ae82c10c..8a514409cd7f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -493,6 +493,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "delegated_task.request": case "delegated_task.remote.request": case "delegated_task.remote.complete": + case "delegated_task.remote.stop": case "delegated_task.wake-policy": case "delegated_task.completion-delivery.acknowledge": case "delegated_task.completion-delivery.dispose": @@ -7528,7 +7529,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // reached the thread after the result is still recorded, but a run that // ended by itself does not settle a stop the task here still owes. if (task.result !== null) { - const owesStop = task.status === "cancelled" || task.status === "interrupted"; + const owesStop = + task.status === "cancelled" || + task.status === "interrupted" || + task.remoteChild?.stoppedThere === false; if ( command.stoppedThere === undefined || task.remoteChild?.stoppedThere === true || @@ -7637,6 +7641,64 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + /** + * Owes a stop to the thread there of a remote task that already has its + * result. Only `remoteChild.stoppedThere` changes, so the result and its + * delivery stand; the follower sends the stop and clears it. + */ + const dispatchRemoteDelegatedTaskStop = Effect.fn( + "orchestrationV2.dispatch.remoteDelegatedTaskStop", + )(function* ( + command: Extract< + OrchestrationV2InternalCommand, + { readonly type: "delegated_task.remote.stop" } + >, + events: Ref.Ref>, + ) { + const { subagents } = yield* projectionStore + .getThreadRecords(command.parentThreadId, ["subagents"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }), + ), + ); + const task = subagents.find( + (candidate) => + candidate.id === command.taskId && + candidate.origin === "app_owned" && + candidate.remoteChild !== undefined && + candidate.result !== null, + ); + if (task?.remoteChild === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Delegated task ${command.taskId} is not a finished remote task of thread ${command.parentThreadId}.`, + }); + } + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "subagent.updated", + threadId: command.parentThreadId, + ...(task.runId === null ? {} : { runId: task.runId }), + nodeId: task.id, + driver: task.driver, + occurredAt: now, + payload: { + ...task, + remoteChild: { + ...task.remoteChild, + stoppedThere: false, + stopCount: (task.remoteChild.stopCount ?? 0) + 1, + }, + updatedAt: now, + }, + }); + }); + // The wait path uses this when its blocking window ends without a terminal // (timeout), so a child that later terminalizes mid-parent-turn still wakes // the parent. Runs under the parent thread's dispatch lock, which is also @@ -11859,6 +11921,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "delegated_task.remote.complete": yield* dispatchRemoteDelegatedTaskComplete(command, events); break; + case "delegated_task.remote.stop": + yield* dispatchRemoteDelegatedTaskStop(command, events); + break; case "delegated_task.wake-policy": yield* dispatchDelegatedTaskWakePolicy(command, events); break; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index d87feed94c57..49aef518a8ed 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -459,7 +459,8 @@ export interface ProjectionStoreV2Shape { >; /** * Delegated tasks in a linked environment with work left for this one: no - * result yet, or cancelled or stopped here without that stop reaching there. + * result yet, or cancelled or stopped here without that stop reaching there, + * including a Stop after the task had its result. */ readonly getOpenRemoteDelegatedTasks: Effect.Effect< ReadonlyArray<{ readonly parentThreadId: ThreadId; readonly taskId: NodeId }>, @@ -6113,6 +6114,7 @@ export const layer: Layer.Layer = json_extract(payload_json, '$.status') IN ('cancelled', 'interrupted') AND json_type(payload_json, '$.remoteChild.stoppedThere') IS NOT 'true' ) + OR json_type(payload_json, '$.remoteChild.stoppedThere') = 'false' ) `.pipe( Effect.map((rows) => diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 60bb6c722625..81b410a46e74 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -110,6 +110,7 @@ function existingThreadIdsForCommand( case "delegated_task.completion-delivery.dispose": case "delegated_task.remote.request": case "delegated_task.remote.complete": + case "delegated_task.remote.stop": return [command.parentThreadId]; case "thread.created.record": return command.parentThreadId === command.targetThreadId @@ -1156,18 +1157,29 @@ const make = Effect.gen(function* () { if (task.origin !== "app_owned") continue; if (task.childThreadId === null) { // A task in a linked environment ends here; its follower then stops it there. - if (task.remoteChild === undefined || task.result !== null) continue; - yield* dispatch({ - type: "delegated_task.remote.complete", - commandId: CommandId.make(`${input.commandId}:stop:${task.id}`), - parentThreadId: input.threadId, - taskId: task.id, - status: "interrupted", - result: - input.reason === undefined - ? "Stopped with its parent." - : `Stopped with its parent: ${input.reason}`, - }).pipe( + // One with its result keeps it, but its thread there may run follow-up work. + if (task.remoteChild === undefined) continue; + const commandId = CommandId.make(`${input.commandId}:stop:${task.id}`); + yield* dispatch( + task.result === null + ? { + type: "delegated_task.remote.complete", + commandId, + parentThreadId: input.threadId, + taskId: task.id, + status: "interrupted", + result: + input.reason === undefined + ? "Stopped with its parent." + : `Stopped with its parent: ${input.reason}`, + } + : { + type: "delegated_task.remote.stop", + commandId, + parentThreadId: input.threadId, + taskId: task.id, + }, + ).pipe( Effect.catch((error) => Effect.logWarning("Unable to stop a delegated task", { parentThreadId: input.threadId, diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 1c101c52a30d..d571491b6e68 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -118,6 +118,8 @@ interface BoxThread { readonly holdRead: Ref.Ref; readonly readStarted: Deferred.Deferred; readonly releaseRead: Deferred.Deferred; + /** Messages sent to the thread there after its launch, each starting a later run. */ + readonly sent: Ref.Ref>; } const makeBoxThread = Effect.gen(function* () { @@ -147,6 +149,7 @@ const makeBoxThread = Effect.gen(function* () { holdRead: yield* Ref.make(false), readStarted: yield* Deferred.make(), releaseRead: yield* Deferred.make(), + sent: yield* Ref.make>([]), } satisfies BoxThread; }); @@ -388,6 +391,13 @@ const boxToolkitLayer = (thread: BoxThread) => { ) : Effect.die(`The box does not expect ${command.type}`), stopDelegatedTasks: (input) => recordStop(input.commandId, "delegated-tasks"), + sendToThread: (input) => + Ref.update(thread.sent, (seen) => [...seen, input.text]).pipe( + Effect.as({ + run: { id: boxLaterRunId, status: "running" }, + delivery: "started", + } as never), + ), }); const layerBoxLaunches = Layer.mock(ThreadLaunch.ThreadLaunchService)({ launch: (input) => @@ -1334,6 +1344,127 @@ it.effect("stopping the parent stops its task there", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +/** Waits until the task here records that the `stopCount`th Stop after its result reached there. */ +const stoppedThere = ( + laptopEnv: Effect.Success>, + taskId: NodeId, + stopCount = 1, +) => + laptopEnv.orchestrator + .streamStoredEventsFrom({ + threadId: parentThreadId, + afterSequence: 0, + eventType: "subagent.updated", + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === taskId && + stored.event.payload.remoteChild?.stoppedThere === true && + stored.event.payload.remoteChild.stopCount === stopCount, + ), + Stream.runHead, + Effect.map((stored) => + Option.isSome(stored) && stored.value.event.type === "subagent.updated" + ? stored.value.event.payload + : undefined, + ), + ); + +it.effect("stopping the parent stops follow-up work on a task there that has its result", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "completed", + result: "All green.", + }); + + // The parent sends the thread there a follow-up, which starts a run there. + const sent = yield* a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Now run the slow suite too.", + }); + expect(sent.isError, JSON.stringify(sent.content)).toBe(false); + expect(yield* Ref.get(thread.sent)).toEqual(["Now run the slow suite too."]); + expect(yield* Ref.get(thread.interrupted)).toBe(0); + + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:laptop-parent-after-result"), + }); + // The thread there is stopped as Stop does, and the task keeps its result. + const task = yield* stoppedThere(a, delegated.taskId); + expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]); + expect(task).toMatchObject({ status: "completed", result: "All green." }); + expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]); + + // A second Stop owes a second stop there, not a replay of the first. + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:laptop-parent-again"), + }); + expect(yield* stoppedThere(a, delegated.taskId, 2)).toMatchObject({ status: "completed" }); + expect(yield* Ref.get(thread.interrupted)).toBe(2); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("a Stop on a task that has its result reaches there after a restart", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build); + // The laptop records the Stop, then goes away before its follower sends it. + const delegated = yield* Effect.scoped( + Effect.gen(function* () { + const before = yield* makeLaptop(database, offers, linking); + yield* linkTo(before.links, b, "full-access"); + yield* seedParent(before); + const task = yield* delegateToBox(before); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(before, task.taskId); + yield* before.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:laptop-parent-before-restart"), + }); + return task; + }), + ); + expect(yield* Ref.get(thread.interrupted)).toBe(0); + + const after = yield* makeLaptop(database, offers, linking); + expect(yield* after.projections.getOpenRemoteDelegatedTasks).toEqual([ + { parentThreadId, taskId: delegated.taskId }, + ]); + yield* after.remote.start(); + expect(yield* stoppedThere(after, delegated.taskId)).toMatchObject({ status: "completed" }); + expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("a parent stopped while the box is unreachable still stops its task there", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 65940ed78bbd..5e6e9503cb04 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -83,7 +83,10 @@ export class RemoteDelegation extends Context.Service< readonly clientRequestId?: string | undefined; }, ) => Effect.Effect; - /** Follows every open remote task until it ends, including after a restart. */ + /** + * Follows every open remote task until it ends, including after a + * restart, and a finished one again when a Stop here owes it a stop there. + */ readonly start: () => Effect.Effect; } >()("t3/peer/RemoteDelegation") {} @@ -315,7 +318,7 @@ const make = Effect.gen(function* () { message: "The delegated task was not recorded.", }); } - yield* follow(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers)); + yield* followOne(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers)); return { taskId }; }); @@ -518,13 +521,16 @@ const make = Effect.gen(function* () { remote, ); // Ended here, maybe while this follower backed off from an unreachable - // machine or before a restart: it still has to be stopped there. + // machine or before a restart: it still has to be stopped there. So + // does one its parent here was stopped after, for what followed there. if (task.result !== null) { if ( - (task.status === "cancelled" || task.status === "interrupted") && - remote.stoppedThere !== true + remote.stoppedThere === false || + ((task.status === "cancelled" || task.status === "interrupted") && + remote.stoppedThere !== true) ) { - yield* stopThere(scope, remote, "stop").pipe( + const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`; + yield* stopThere(scope, remote, key).pipe( // Its thread there now runs above what this side may touch, say // because the parent here was lowered since; no retry changes that. Effect.catchIf(isModeRefusal, (error) => @@ -534,7 +540,13 @@ const make = Effect.gen(function* () { }), ), ); - yield* complete(parentThreadId, taskId, task.status, task.result, "stopped"); + yield* complete( + parentThreadId, + taskId, + terminalStatus(task.status), + task.result, + "stopped", + ); } return true; } @@ -620,6 +632,42 @@ const make = Effect.gen(function* () { ), ); + const following = new Map(); + + /** + * `follow`, at most once per task. Asked again while it runs, say by a + * Stop here on a task that already has its result, it looks once more + * before it ends, so that stop is not missed. + */ + const followOne = (parentThreadId: ThreadId, taskId: NodeId) => + Effect.suspend(() => { + const running = following.get(taskId); + if (running !== undefined) { + running.again = true; + return Effect.void; + } + const state = { again: false }; + following.set(taskId, state); + return follow(parentThreadId, taskId).pipe( + // Checked and released in one step, so a request between them is never lost. + Effect.repeat({ + while: () => { + if (state.again) { + state.again = false; + return true; + } + following.delete(taskId); + return false; + }, + }), + Effect.ensuring( + Effect.sync(() => { + if (following.get(taskId) === state) following.delete(taskId); + }), + ), + ); + }); + const cancel: RemoteDelegation["Service"]["cancel"] = (scope, task, input) => Effect.gen(function* () { const remote = task.remoteChild; @@ -684,10 +732,21 @@ const make = Effect.gen(function* () { const start: RemoteDelegation["Service"]["start"] = () => forkParked( Effect.gen(function* () { + // A finished task's follower has ended, so a Stop here that owes its + // thread there a stop starts it again. Started before the scan below; + // a Stop that slips between the two stays owed for the next start. + yield* Stream.runForEach(threads.streamDomainEvents, (event) => + event.type === "subagent.updated" && event.payload.remoteChild?.stoppedThere === false + ? followOne(event.threadId, event.payload.id).pipe(Effect.forkIn(followers)) + : Effect.void, + ).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkIn(followers, { startImmediately: true }), + ); const open = yield* projections.getOpenRemoteDelegatedTasks; yield* Effect.forEach( open, - ({ parentThreadId, taskId }) => follow(parentThreadId, taskId), + ({ parentThreadId, taskId }) => followOne(parentThreadId, taskId), { concurrency: "unbounded", discard: true, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8f69b6b39bcd..2bc7496fcb18 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -750,8 +750,14 @@ export const OrchestrationV2RemoteTaskChild = Schema.Struct({ * task's run that ended there by itself also sets it, unless the task here * was cancelled or stopped, which still owes a stop for whatever runs on the * thread there now. Its follower keeps sending that stop, across restarts. + * `false` is a stop owed by a Stop here on a task that already had its result. */ stoppedThere: Schema.optional(Schema.Boolean), + /** + * Stops asked for here once the task had its result. The count names the + * one owed, so each reaches the thread there once however often it is sent. + */ + stopCount: Schema.optional(NonNegativeInt), }); export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type; @@ -3144,6 +3150,19 @@ const OrchestrationV2InternalCommand = Schema.Union([ */ stoppedThere: Schema.optional(Schema.Literals(["ran-out", "stopped"])), }), + /** + * Owes a stop to the thread there of a remote task that already has its + * result, as Stop on a parent stops a finished child here: whatever runs on + * that thread now is stopped. The task keeps its status, result and + * completion delivery; its follower sends the stop and reports it with + * `delegated_task.remote.complete`. + */ + Schema.Struct({ + type: Schema.Literal("delegated_task.remote.stop"), + commandId: CommandId, + parentThreadId: ThreadId, + taskId: NodeId, + }), Schema.Struct({ type: Schema.Literal("checkpoint.rollback.fail"), commandId: CommandId, From e744eb6c19281ec0ce3fefe357e952fb860eb3e3 Mon Sep 17 00:00:00 2001 From: Lenori <122464369+Lenoridev@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:48:50 +0200 Subject: [PATCH 123/408] fix(server): acknowledge only the matching remote stop generation --- .../src/orchestration-v2/Orchestrator.ts | 5 ++ .../RemoteDelegatedTask.test.ts | 67 +++++++++++++++++++ apps/server/src/peer/RemoteDelegation.test.ts | 63 +++++++++++++++++ apps/server/src/peer/RemoteDelegation.ts | 18 ++++- packages/contracts/src/orchestrationV2.ts | 2 + 5 files changed, 153 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8a514409cd7f..63c177f8c702 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7520,6 +7520,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Delegated task ${command.taskId} is not a remote task of thread ${command.parentThreadId}.`, }); } + if ( + command.stoppedThere === "stopped" && + (command.stopCount ?? 0) !== (task.remoteChild?.stopCount ?? 0) + ) + return; const remoteChild = command.stoppedThere === undefined ? task.remoteChild diff --git a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts index f7c0164d775b..d4f5232c5834 100644 --- a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts +++ b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts @@ -225,6 +225,73 @@ it.layer(layerTest)("a delegated task in a linked environment", (it) => { }), ); + it.effect("keeps a newer stop recoverable after an older acknowledgement", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const parent = yield* seedLiveParent("stop-generation"); + yield* orchestrator.dispatch({ + type: "delegated_task.remote.request", + commandId: CommandId.make("command:remote-delegate:stop-generation"), + parentThreadId: parent.threadId, + parentRunId: parent.runId, + parentNodeId: parent.rootNodeId, + task: "Run a check.", + driver: ProviderDriverKind.make("remote"), + modelSelection, + remoteChild, + }); + const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; + const openFor = projections.getOpenRemoteDelegatedTasks.pipe( + Effect.map((open) => open.filter((entry) => entry.parentThreadId === parent.threadId)), + ); + const complete = { + type: "delegated_task.remote.complete" as const, + parentThreadId: parent.threadId, + taskId: task.id, + status: "completed" as const, + result: "Original result.", + }; + yield* orchestrator.dispatch({ + ...complete, + commandId: CommandId.make("command:result:stop-generation"), + stoppedThere: "ran-out", + }); + for (const count of [1, 2]) { + yield* orchestrator.dispatch({ + type: "delegated_task.remote.stop", + parentThreadId: parent.threadId, + taskId: task.id, + commandId: CommandId.make(`command:stop-generation:${count}`), + }); + } + // Reports from before generation tracking cannot clear a later numbered Stop either. + for (const stopCount of [undefined, 1]) { + const rejected = yield* orchestrator + .dispatch({ + ...complete, + commandId: CommandId.make(`command:stale-stop:${stopCount}`), + stoppedThere: "stopped", + ...(stopCount === undefined ? {} : { stopCount }), + }) + .pipe(Effect.flip); + assert.equal(rejected._tag, "OrchestratorDispatchError"); + assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: task.id }]); + } + yield* orchestrator.dispatch({ + ...complete, + commandId: CommandId.make("command:current-stop:2"), + stoppedThere: "stopped", + stopCount: 2, + }); + const settled = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; + assert.equal(settled.result, "Original result."); + assert.equal(settled.status, "completed"); + assert.equal(settled.remoteChild?.stoppedThere, true); + assert.deepEqual(yield* openFor, []); + }), + ); + it.effect("wakes its parent with the result when it completes there", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index d571491b6e68..7f3e78873b37 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -118,6 +118,9 @@ interface BoxThread { readonly holdRead: Ref.Ref; readonly readStarted: Deferred.Deferred; readonly releaseRead: Deferred.Deferred; + readonly holdFirstStop: Ref.Ref; + readonly stopStarted: Deferred.Deferred; + readonly releaseStop: Deferred.Deferred; /** Messages sent to the thread there after its launch, each starting a later run. */ readonly sent: Ref.Ref>; } @@ -149,6 +152,9 @@ const makeBoxThread = Effect.gen(function* () { holdRead: yield* Ref.make(false), readStarted: yield* Deferred.make(), releaseRead: yield* Deferred.make(), + holdFirstStop: yield* Ref.make(false), + stopStarted: yield* Deferred.make(), + releaseStop: yield* Deferred.make(), sent: yield* Ref.make>([]), } satisfies BoxThread; }); @@ -387,6 +393,13 @@ const boxToolkitLayer = (thread: BoxThread) => { dispatch: (command) => command.type === "thread.stop" ? recordStop(command.commandId, "thread.stop").pipe( + Effect.tap(() => + Effect.gen(function* () { + if (!(yield* Ref.getAndSet(thread.holdFirstStop, false))) return; + yield* Deferred.succeed(thread.stopStarted, undefined); + yield* Deferred.await(thread.releaseStop); + }), + ), Effect.as({ sequence: 0, storedEvents: [] } as never), ) : Effect.die(`The box does not expect ${command.type}`), @@ -1425,6 +1438,56 @@ it.effect("stopping the parent stops follow-up work on a task there that has its ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("a delayed Stop acknowledgement leaves a newer Stop owed", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(a, delegated.taskId); + + yield* Ref.set(thread.holdFirstStop, true); + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:delayed-first"), + }); + yield* Deferred.await(thread.stopStarted); + // Work starts after the first Stop landed there, but before its acknowledgement returns. + yield* a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Run another check.", + }); + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:delayed-second"), + }); + const pending = yield* a.threads.getThreadRecords(parentThreadId, ["subagents"]); + expect( + pending.subagents.find((task) => task.id === delegated.taskId)?.remoteChild, + ).toMatchObject({ stoppedThere: false, stopCount: 2 }); + yield* Deferred.succeed(thread.releaseStop, undefined); + expect(yield* stoppedThere(a, delegated.taskId, 2)).toMatchObject({ + status: "completed", + result: "All green.", + }); + expect(yield* Ref.get(thread.interrupted)).toBe(2); + expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("a Stop on a task that has its result reaches there after a restart", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 5e6e9503cb04..8aa8729f2c34 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -335,6 +335,7 @@ const make = Effect.gen(function* () { status: "completed" | "failed" | "cancelled" | "interrupted", result: string, stoppedThere: "ran-out" | "stopped" | undefined, + stopCount?: number, ) => Effect.gen(function* () { const attempt = yield* crypto.randomUUIDv4().pipe(Effect.orDie); @@ -347,6 +348,7 @@ const make = Effect.gen(function* () { status, result, ...(stoppedThere === undefined ? {} : { stoppedThere }), + ...(stopCount === undefined ? {} : { stopCount }), }) .pipe( Effect.catch((error) => @@ -497,7 +499,9 @@ const make = Effect.gen(function* () { const reason = yield* finalReason(parentThreadId, taskId, error); if (reason === undefined) return yield* error; // Gone there, or no link to reach it by: nothing left to stop there. - yield* complete(parentThreadId, taskId, "failed", reason, "stopped"); + const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); + const stopCount = subagents.find((task) => task.id === taskId)?.remoteChild?.stopCount; + yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount); }), }), Effect.retry(backoff), @@ -546,7 +550,9 @@ const make = Effect.gen(function* () { terminalStatus(task.status), task.result, "stopped", + remote.stopCount, ); + return yield* settled(parentThreadId, taskId); } return true; } @@ -687,7 +693,14 @@ const make = Effect.gen(function* () { // Best effort: the result stands whether or not the stop gets there. yield* stopThere(there, remote, key, reason).pipe( Effect.andThen( - complete(task.threadId, task.id, terminalStatus(task.status), task.result, "stopped"), + complete( + task.threadId, + task.id, + terminalStatus(task.status), + task.result, + "stopped", + remote.stopCount, + ), ), Effect.ignoreCause({ log: true }), ); @@ -714,6 +727,7 @@ const make = Effect.gen(function* () { ? cancelled : `${cancelled} It could not be stopped in ${remote.label} and may still run there: ${unstopped}`, unstopped === undefined ? "stopped" : undefined, + remote.stopCount, ).pipe( Effect.mapError( (error) => diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 2bc7496fcb18..3d4b0dbdad2e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3149,6 +3149,8 @@ const OrchestrationV2InternalCommand = Schema.Union([ * a run that ended by itself leaves the stop owed for what may follow it. */ stoppedThere: Schema.optional(Schema.Literals(["ran-out", "stopped"])), + /** The stop generation this report acknowledges; absent for the original unnumbered stop. */ + stopCount: Schema.optional(NonNegativeInt), }), /** * Owes a stop to the thread there of a remote task that already has its From 072d343abf2641fe8954d23a84fecb4c4611f339 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:10:01 -0700 Subject: [PATCH 124/408] fix(server): a remote task refuses worktree isolation, and its failures keep the cause delegate_task with environmentId launched in the linked project's checkout even when isolation "worktree" was asked for. A worktree there would branch from a commit this checkout has and the other may not, so the call is refused before launching, pointing at t3_thread_launch with a worktree workspaceStrategy. Recording the task or its cancellation no longer builds the caller's message from the dispatch error; the cause goes to the log and the caller gets a fixed message. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/RemoteDelegation.test.ts | 25 +++++++++++++++++ apps/server/src/peer/RemoteDelegation.ts | 27 ++++++++++++++++--- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 7f3e78873b37..9e71f7836d4b 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -870,6 +870,31 @@ it.effect("a task named only by environment inherits the parent's model, within ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("refuses worktree isolation for a task there before launching anything", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "auto"); + yield* seedParent(a); + + const result = yield* a.call("delegate_task", { + task: "Run the suite on the box.", + target: { environmentId: box.environmentId }, + isolation: "worktree", + }); + expect(result.isError).toBe(true); + expect(JSON.stringify(result.content)).toContain("isolation"); + expect(yield* Ref.get(thread.launched)).toBeNull(); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("follows an open task again after the laptop restarts", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 8aa8729f2c34..3f8d6beb2c91 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -194,6 +194,15 @@ const make = Effect.gen(function* () { } const parentNodeId = parentRun.rootNodeId; const { target } = input; + // A worktree there would branch from a commit this checkout has and the + // other may not, so a remote task runs in that project's checkout. + if (input.isolation === "worktree") { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', + }); + } // The provider and model inherit as they do for a task here. Another // provider there has no model to inherit, so the caller names one. const inherited = parent.thread.modelSelection; @@ -282,11 +291,18 @@ const make = Effect.gen(function* () { completionWake: input.mode === "wait" ? "settled_only" : "always", }) .pipe( + // The cause goes to the log; the caller learns only that recording failed. + Effect.tapError((cause) => + Effect.logWarning("remote-delegation.record-failed", { + parentThreadId: scope.thread.threadId, + cause, + }), + ), Effect.mapError( - (error) => + () => new OrchestratorMcpFailure({ code: "orchestration_error", - message: `Unable to record the delegated task: ${error.message}`, + message: "Unable to record the delegated task.", }), ), // Nothing here follows a thread the task was never recorded for, so stop it there. @@ -729,11 +745,14 @@ const make = Effect.gen(function* () { unstopped === undefined ? "stopped" : undefined, remote.stopCount, ).pipe( + Effect.tapError((cause) => + Effect.logWarning("remote-delegation.cancel-record-failed", { taskId: task.id, cause }), + ), Effect.mapError( - (error) => + () => new OrchestratorMcpFailure({ code: "orchestration_error", - message: `Unable to record the cancellation: ${error.message}`, + message: "Unable to record the cancellation.", }), ), ); From ab7da8f9f3d4ea3dc687b18f0ee35638a794c526 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:29:21 -0700 Subject: [PATCH 125/408] fix(web,mobile): a task a linked environment runs shows under its parent delegate_task to a linked environment launches an ordinary thread there, marked delegatedFrom, so a client connected to both machines listed it in the sidebar as well as in the parent's lineage panel. Its approvals and questions also never reached the parent here. Lists now treat such a thread as a subagent when the client also lists the thread that delegated it: the web sidebar and its project ordering, mobile's thread lists, and notifications leave it out. A parent here is flagged, and shows the "subagent needs input" banner, when the task or one of its own subagents there asks. A task whose parent the client cannot list (that machine switched off, or the parent gone) stays listed on its own, so its work is never out of reach. Co-Authored-By: Claude Opus 5.5 --- .../home/useThreadListActions.test.ts | 5 +- .../src/features/home/useThreadListActions.ts | 2 +- apps/mobile/src/state/thread-order.test.ts | 6 +- apps/mobile/src/state/thread-order.ts | 4 +- apps/web/src/components/LegacySidebar.tsx | 18 +- apps/web/src/components/Sidebar.logic.test.ts | 3 +- apps/web/src/components/Sidebar.logic.ts | 26 ++- apps/web/src/components/Sidebar.tsx | 16 +- ...ficationCoordinator.badge.browser.test.tsx | 16 ++ .../ThreadNotificationCoordinator.tsx | 22 ++- .../chat/ThreadRelationshipsControl.tsx | 4 +- apps/web/src/hooks/useSidebarProjectGroups.ts | 5 +- apps/web/src/state/entities.ts | 5 + .../src/state/threadShell.test.ts | 80 ++++++++ .../client-runtime/src/state/threadShell.ts | 186 ++++++++++++++---- 15 files changed, 337 insertions(+), 61 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 9a59367a9543..ec0f6a14558d 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -114,7 +114,10 @@ vi.mock("../../state/thread-order", () => ({ }, })); vi.mock("../../state/threads", () => ({ - environmentThreadShells: { threadShellsAtom: "thread-shells" }, + environmentThreadShells: { + threadShellsAtom: "thread-shells", + navigationThreadShellsAtom: "thread-shells", + }, threadEnvironment: Object.fromEntries( [ "archive", diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 0f18f24923cc..f6eb7f62a59f 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -615,7 +615,7 @@ export function useThreadListActions(): { const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => { if (!checkThreadOperationPermission(thread, "Could not move thread")) return false; if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false; - const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom); + const shells = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom); const current = shells.find( (row) => row.id === thread.id && row.environmentId === thread.environmentId, ); diff --git a/apps/mobile/src/state/thread-order.test.ts b/apps/mobile/src/state/thread-order.test.ts index cf5a59b052b6..12e1d1a2fb52 100644 --- a/apps/mobile/src/state/thread-order.test.ts +++ b/apps/mobile/src/state/thread-order.test.ts @@ -19,7 +19,9 @@ vi.mock("./atom-registry", async () => { }); vi.mock("./threads", async () => { const { Atom } = await import("effect/reactivity"); - return { environmentThreadShells: { threadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) } }; + return { + environmentThreadShells: { navigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) }, + }; }); vi.mock("./server", async () => { const { Atom } = await import("effect/reactivity"); @@ -30,7 +32,7 @@ vi.mock("./use-thread-outbox", async () => { return { queuedThreadKeysAtom: Atom.make(new Set()).pipe(Atom.keepAlive) }; }); -const shellsAtom = environmentThreadShells.threadShellsAtom as Atom.Writable< +const shellsAtom = environmentThreadShells.navigationThreadShellsAtom as Atom.Writable< readonly EnvironmentThreadShell[], readonly EnvironmentThreadShell[] >; diff --git a/apps/mobile/src/state/thread-order.ts b/apps/mobile/src/state/thread-order.ts index 5625ec467b4a..e5f82a1277ed 100644 --- a/apps/mobile/src/state/thread-order.ts +++ b/apps/mobile/src/state/thread-order.ts @@ -51,7 +51,7 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) { if (current === null) return; const configs = appAtomRegistry.get(environmentServerConfigsAtom); const ordered = getThreadListV2OrderedSection({ - threads: appAtomRegistry.get(environmentThreadShells.threadShellsAtom), + threads: appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom), section: current.section, now: new Date().toISOString(), queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom), @@ -73,7 +73,7 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) { refreshPendingOrder = refresh; appAtomRegistry.set(pendingThreadOrderAtom, pending); unsubscribers.push( - appAtomRegistry.subscribe(environmentThreadShells.threadShellsAtom, refresh), + appAtomRegistry.subscribe(environmentThreadShells.navigationThreadShellsAtom, refresh), appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh), appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh), ); diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index 9076b9c127ce..0ea4738f9799 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -90,6 +90,7 @@ import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { readThreadShell, useProjects, + useDelegatedUnderParent, useThreadShells, useThreadShellsForProjectRefs, waitForProjectRemoval, @@ -1114,6 +1115,7 @@ function useProjectThreads(project: SidebarProjectSnapshot) { (settings) => settings.sidebarThreadSortOrder, ); const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs); + const delegatedUnderParent = useDelegatedUnderParent(); const threadLastVisitedAts = useUiStateStore( useShallow((state) => sidebarThreads.map( @@ -1158,7 +1160,7 @@ function useProjectThreads(project: SidebarProjectSnapshot) { ]), ); const visibleProjectThreads = sortThreads( - filterSidebarV2VisibleThreads(sidebarThreads, null), + filterSidebarV2VisibleThreads(sidebarThreads, null, delegatedUnderParent), threadSortOrder, ); const projectStatus = resolveProjectStatusIndicator( @@ -3097,6 +3099,7 @@ function useSortedLegacySidebarProjects(input: { sidebarProjectSortOrder, } = input; const sidebarThreads = useThreadShells(); + const delegatedUnderParent = useDelegatedUnderParent(); const sidebarProjectByKey = new Map( sidebarProjects.map((project) => [project.projectKey, project] as const), ); @@ -3104,7 +3107,11 @@ function useSortedLegacySidebarProjects(input: { ...project, id: project.projectKey, })); - const sortableThreads = filterSidebarV2VisibleThreads(sidebarThreads, null).map((thread) => { + const sortableThreads = filterSidebarV2VisibleThreads( + sidebarThreads, + null, + delegatedUnderParent, + ).map((thread) => { const physicalKey = projectPhysicalKeyByScopedRef.get( scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), @@ -3147,6 +3154,7 @@ function useLegacySidebarThreads(input: { expandedThreadListsByProject, } = input; const sidebarThreads = useThreadShells(); + const delegatedUnderParent = useDelegatedUnderParent(); const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); const sidebarThreadByKey = new Map( sidebarThreads.map( @@ -3177,7 +3185,11 @@ function useLegacySidebarThreads(input: { } const visibleSidebarThreadKeys = sortedProjects.flatMap((project) => { const projectThreads = sortThreads( - filterSidebarV2VisibleThreads(threadsByProjectKey.get(project.projectKey) ?? [], null), + filterSidebarV2VisibleThreads( + threadsByProjectKey.get(project.projectKey) ?? [], + null, + delegatedUnderParent, + ), sidebarThreadSortOrder, ); const projectExpanded = resolveProjectExpanded( diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 18197317cd19..fc5d45dfad32 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1,4 +1,5 @@ import { presentThreadShell } from "@t3tools/client-runtime/state/models"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; import * as DateTime from "effect/DateTime"; import { deriveActiveWorkStartedAt } from "../session-logic.ts"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -826,7 +827,7 @@ describe("sortSidebarV2ProjectGroups", () => { ]; expect( - sortSidebarV2ProjectGroups(projects, threads, "updated_at").map( + sortSidebarV2ProjectGroups(projects, threads, "updated_at", new Set()).map( (project) => project.projectKey, ), ).toEqual(["logical-newer", "logical-older"]); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index e5bcdffc980c..bc9653515e2e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,4 +1,5 @@ import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; +import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; import * as React from "react"; @@ -536,16 +537,27 @@ export function resolveSidebarRowThreadId( return thread?.id ?? threadId; } +/** + * `delegatedUnderParent` holds the tasks linked environments run for a thread + * the sidebar lists, by thread key; they show under that thread, as subagents do. + */ export function filterSidebarV2VisibleThreads< - T extends Pick & { - environmentId: string; + T extends Pick & { projectId: string; }, ->(threads: readonly T[], scopedProjectKeys: ReadonlySet | null): T[] { +>( + threads: readonly T[], + scopedProjectKeys: ReadonlySet | null, + delegatedUnderParent: ReadonlySet, +): T[] { return threads.filter( (thread) => thread.archivedAt === null && - !isSidebarSubagentThread(thread) && + !isShownUnderParent( + { environmentId: thread.environmentId, threadId: thread.id }, + thread.lineage, + delegatedUnderParent, + ) && (scopedProjectKeys === null || scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), ); @@ -1303,15 +1315,17 @@ export function sortLogicalProjectsForSidebar< export function sortSidebarV2ProjectGroups< TProject extends LogicalSidebarProject, - TThread extends ScopedSidebarThread & Pick, + TThread extends ScopedSidebarThread & + Pick, >( projects: readonly TProject[], threads: readonly TThread[], sortOrder: SidebarProjectSortOrder, + delegatedUnderParent: ReadonlySet, ): TProject[] { return sortLogicalProjectsForSidebar( projects, - filterSidebarV2VisibleThreads(threads, null), + filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent), sortOrder, ); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 9447ce0ba661..244dc14f1adc 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -114,6 +114,7 @@ import { import { readThreadShell, useAllEnvironmentProjectSnapshotsReady, + useDelegatedUnderParent, useProjects, useServerConfigs, useQuietThreadShells, @@ -288,6 +289,8 @@ type SidebarOptimisticDrop = { interface SidebarThreadPartitionInput { readonly threads: readonly EnvironmentThreadShell[]; readonly scopedProjectKeys: ReadonlySet | null; + /** Tasks linked environments run for a listed thread; they show under it. */ + readonly delegatedUnderParent: ReadonlySet; readonly serverConfigs: ReadonlyMap; readonly optimisticDrop: SidebarOptimisticDrop | null; readonly workingShelfEnabled: boolean; @@ -370,6 +373,7 @@ function useSidebarThreads(input: { ), ), ); + const delegatedUnderParent = useDelegatedUnderParent(); const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled); const nowMinute = useNowMinute(); // Snooze wake times are second-precise, so classifying with the quantized @@ -409,6 +413,7 @@ function useSidebarThreads(input: { const partition = partitionSidebarThreads({ threads, scopedProjectKeys, + delegatedUnderParent, serverConfigs, optimisticDrop, workingShelfEnabled, @@ -501,9 +506,16 @@ function useSidebarThreads(input: { } function partitionSidebarThreads(input: SidebarThreadPartitionInput) { - const { threads, scopedProjectKeys, serverConfigs, optimisticDrop, workingShelfEnabled } = input; + const { + threads, + scopedProjectKeys, + delegatedUnderParent, + serverConfigs, + optimisticDrop, + workingShelfEnabled, + } = input; const preciseNow = new Date().toISOString(); - const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys); + const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); inboxReturns.observe(workingShelfEnabled ? threads : null); const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx index dd537f2a8d0b..b8d679f77bcc 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx @@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({ sound: vi.fn(), badge: vi.fn(), environmentIds: ["one", "two"], + noDelegated: new Set(), })); vi.mock(import("@tanstack/react-router"), async (original) => ({ ...(await original()), @@ -40,6 +41,20 @@ vi.mock(import("../state/environments"), async (original) => ({ ...(await original()), useEnvironmentIds: (() => state.environmentIds) as never, })); +vi.mock(import("../state/threads"), async (original) => { + const actual = await original(); + return { + ...actual, + environmentThreadShells: { + ...actual.environmentThreadShells, + pendingSubagentRequestsAtom: (() => noRequestsAtom) as never, + }, + }; +}); +vi.mock(import("../state/entities"), async (original) => ({ + ...(await original()), + useDelegatedUnderParent: (() => state.noDelegated) as never, +})); vi.mock(import("../hooks/useSettings"), async (original) => ({ ...(await original()), useClientSettings: (( @@ -58,6 +73,7 @@ import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator"; let registry: AtomRegistry.AtomRegistry; const shellAtom = Atom.family((_id: string) => Atom.make(null)); +const noRequestsAtom = Atom.make(new Map()); state.shells = { set: (id, value) => registry.set(shellAtom(id), value) }; class TestNotification extends EventTarget { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index c9355fc7f820..4a2b30efc72e 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -2,7 +2,7 @@ import { type PendingSubagentRequest, presentThreadShell, } from "@t3tools/client-runtime/state/models"; -import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads"; +import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import { useAtomValue } from "@effect/atom-react"; import { useNavigate, useParams } from "@tanstack/react-router"; import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; @@ -17,7 +17,9 @@ import { useEffect, useRef } from "react"; import { getClientSettings, useClientSettings } from "../hooks/useSettings"; import { useEnvironmentIds } from "../state/environments"; +import { useDelegatedUnderParent } from "../state/entities"; import { environmentShell } from "../state/shell"; +import { environmentThreadShells } from "../state/threads"; import { hasDesktopNotifications, hasNotificationSound, @@ -110,6 +112,11 @@ function EnvironmentNotifications({ const shell = useAtomValue(environmentShell.stateValueAtom(environmentId)); const threads = shell.status === "live" && Option.isSome(shell.snapshot) ? shell.snapshot.value.threads : null; + // A parent here also hears of what its tasks on linked environments ask. + const subagentRequests = useAtomValue( + environmentThreadShells.pendingSubagentRequestsAtom(environmentId), + ); + const delegatedUnderParent = useDelegatedUnderParent(); const mode = useClientSettings((settings) => settings.notificationMode); const inAppNotificationsEnabled = useClientSettings( (settings) => settings.inAppNotificationsEnabled, @@ -126,9 +133,16 @@ function EnvironmentNotifications({ return; } const next = new Map(); - const subagentRequests = pendingSubagentRequestsByThread(threads); for (const rawThread of threads) { - if (rawThread.lineage.relationshipToParent === "subagent") continue; + if ( + isShownUnderParent( + { environmentId, threadId: rawThread.id }, + rawThread.lineage, + delegatedUnderParent, + ) + ) { + continue; + } const prior = previous.current.get(rawThread.id); const subagentRequest = subagentRequests.get(rawThread.id) ?? null; if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) { @@ -242,11 +256,13 @@ function EnvironmentNotifications({ }, [ activeEnvironmentId, activeThreadId, + delegatedUnderParent, environmentId, inAppNotificationsEnabled, mode, navigate, onNotification, + subagentRequests, threads, ]); diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 24998eee7e8a..9e2e39428ef8 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -771,9 +771,9 @@ export function ThreadRelationshipsPanel(props: { key={agent.id} agent={agent} // Its provider instance belongs to the environment it runs in. - provider={serverConfigs + provider={providersByEnvironment .get(agent.remoteChild.environmentId) - ?.providers.find((entry) => entry.instanceId === agent.providerInstanceId)} + ?.find((entry) => entry.instanceId === agent.providerInstanceId)} /> ))} diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index cb1b3b101326..5f4008aea482 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -2,7 +2,7 @@ import { orderItemsByPreferredIds, sortSidebarV2ProjectGroups } from "../compone import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject"; import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping"; import { useEnvironmentIdentities, usePrimaryEnvironmentId } from "../state/environments"; -import { useProjects, useQuietThreadShells } from "../state/entities"; +import { useDelegatedUnderParent, useProjects, useQuietThreadShells } from "../state/entities"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useClientSettings } from "./useSettings"; @@ -11,6 +11,7 @@ export function useSidebarProjectGroups() { // Activity order lags a running thread's streaming ticks until its next // real change; reading every tick re-rendered the whole sidebar with it. const threads = useQuietThreadShells(); + const delegatedUnderParent = useDelegatedUnderParent(); const projectOrder = useUiStateStore((store) => store.projectOrder); const sortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); const groupingSettings = useClientSettings(selectProjectGroupingSettings); @@ -35,5 +36,5 @@ export function useSidebarProjectGroups() { primaryEnvironmentId, resolveEnvironmentLabel: (environmentId) => labels.get(environmentId) ?? null, }); - return sortSidebarV2ProjectGroups(unsortedGroups, threads, sortOrder); + return sortSidebarV2ProjectGroups(unsortedGroups, threads, sortOrder, delegatedUnderParent); } diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 012bbb82ce25..a3f744eba1a3 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -116,6 +116,11 @@ export function useAllEnvironmentProjectSnapshotsReady(): boolean { return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom); } +/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */ +export function useDelegatedUnderParent(): ReadonlySet { + return useAtomValue(environmentThreadShells.delegatedUnderParentAtom); +} + export function useThreadShellsForProjectRefs( refs: ReadonlyArray, ): ReadonlyArray { diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 2dcc3233db3a..8988cac30149 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -215,6 +215,86 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); + it("lists a task a linked environment runs for a listed thread under that thread", () => { + const { registry, threads, snapshotAtom, catalogValueAtom } = makeHarness([ + environmentId, + remoteEnvironmentId, + ]); + const parent = v2ThreadShell; + const task = { + ...v2ThreadShell, + id: ThreadId.make("remote-task"), + creationSource: "mcp" as const, + status: "running" as const, + activityRunStatus: "running" as const, + delegatedFrom: { environmentId, threadId: parent.id, title: parent.title }, + }; + const helper = { + ...task, + id: ThreadId.make("remote-helper"), + delegatedFrom: undefined, + lineage: { + ...task.lineage, + parentThreadId: task.id, + relationshipToParent: "subagent" as const, + }, + }; + const approval = { + id: RuntimeRequestId.make("cat-file"), + kind: "command" as const, + createdAt: v2Now, + }; + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] }); + registry.set(snapshotAtom(remoteEnvironmentId), { + ...v2ShellSnapshot, + threads: [task, helper], + }); + const parentRef = { environmentId, threadId: parent.id }; + const inputs = threads.childThreadInputsAtom(parentRef); + const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom); + const disposeParent = registry.mount(threads.threadShellAtom(parentRef)); + const disposeInputs = registry.mount(inputs); + const listed = () => + registry + .get(threads.navigationThreadShellsAtom) + .map((thread) => `${thread.environmentId}/${thread.id}`); + expect(listed()).toEqual([`${environmentId}/${parent.id}`]); + + // The helper the task started there asks for approval: the parent here hears of it. + registry.set(snapshotAtom(remoteEnvironmentId), { + ...v2ShellSnapshot, + threads: [task, { ...helper, pendingRuntimeRequest: approval }], + }); + expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe( + "approval", + ); + expect(registry.get(inputs).map((thread) => `${thread.environmentId}/${thread.id}`)).toEqual([ + `${remoteEnvironmentId}/${helper.id}`, + ]); + + // A task whose parent is gone there is listed on its own, as is one whose + // parent's environment is switched off. + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] }); + expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]); + // Archiving the parent here leaves the task there unarchived, so it is listed on its own. + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [{ ...parent, archivedAt: v2Now }], + }); + expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]); + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] }); + expect(listed()).toEqual([`${environmentId}/${parent.id}`]); + const catalog = registry.get(catalogValueAtom); + const entries = new Map(catalog.entries); + entries.set(environmentId, { ...entries.get(environmentId)!, enabled: false }); + registry.set(catalogValueAtom, { ...catalog, entries }); + expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]); + disposeInputs(); + disposeParent(); + disposeNavigation(); + registry.dispose(); + }); + it.each([ { reason: "switched-off", state: { enabled: false } }, { diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 8d61ff6ac567..6355226969c1 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -45,6 +45,20 @@ const isChildRunLive = ( thread.status === "running" || thread.status === "waiting"; +/** + * Whether a thread shows under its parent rather than in thread lists: a + * subagent, or a task a linked environment delegated here whose parent the + * client lists (`delegatedUnderParent`, by thread key). A task whose parent + * the client cannot list stays in the lists, so its work is never out of reach. + */ +export function isShownUnderParent( + ref: ScopedThreadRef, + lineage: OrchestrationV2ThreadShell["lineage"], + delegatedUnderParent: ReadonlySet, +): boolean { + return lineage.relationshipToParent === "subagent" || delegatedUnderParent.has(threadKey(ref)); +} + /** Provider-native subagents ask on their parent, so they are skipped. */ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null { @@ -52,7 +66,7 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq if ( kind === undefined || kind === "auth_refresh" || - thread.lineage.relationshipToParent !== "subagent" || + (thread.lineage.relationshipToParent !== "subagent" && thread.delegatedFrom === undefined) || isProviderNativeSubagentThread(thread) || !isChildRunLive(thread) ) { @@ -61,28 +75,51 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq return kind === "user_input" ? "user_input" : "approval"; } -export function pendingSubagentRequestsByThread( +/** + * The threads to flag for a subagent's live question or approval, up its + * subagent chain. `delegated` are tasks this environment's threads delegated + * to linked environments, with what each one, or its own subagents, asks. + */ +function pendingSubagentRequestsByThread( threads: ReadonlyArray, + delegated: ReadonlyArray<{ + readonly parentThreadId: ThreadId; + readonly request: PendingSubagentRequest; + }> = [], ): ReadonlyMap { const requests = new Map(); let byId: ReadonlyMap | undefined; - for (const child of threads) { - const request = subagentRequest(child); - if (request === null) continue; + const flag = ( + firstParentId: ThreadId | null, + request: PendingSubagentRequest, + seen: Set, + ) => { byId ??= new Map(threads.map((thread) => [thread.id, thread] as const)); - const seen = new Set([child.id]); - let current: OrchestrationV2ThreadShell | undefined = child; - while (current?.lineage.relationshipToParent === "subagent") { - const parentId: ThreadId | null = current.lineage.parentThreadId; - if (parentId === null || seen.has(parentId)) break; + let parentId = firstParentId; + while (parentId !== null && !seen.has(parentId)) { seen.add(parentId); if (requests.get(parentId) !== "approval") requests.set(parentId, request); - current = byId.get(parentId); + const parent = byId.get(parentId); + parentId = + parent?.lineage.relationshipToParent === "subagent" ? parent.lineage.parentThreadId : null; } + }; + for (const child of threads) { + if (child.lineage.relationshipToParent !== "subagent") continue; + const request = subagentRequest(child); + if (request !== null) flag(child.lineage.parentThreadId, request, new Set([child.id])); } + for (const task of delegated) flag(task.parentThreadId, task.request, new Set()); return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests; } +const sameRequests = ( + left: ReadonlyMap, + right: ReadonlyMap, +) => + left.size === right.size && + [...right].every(([threadId, request]) => left.get(threadId) === request); + export function childThreadInputsTitle( children: ReadonlyArray>, ): string { @@ -177,16 +214,40 @@ export function createEnvironmentThreadShellAtoms(input: { }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)), ); - const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => { + // What an environment's own subagents ask. Kept apart from the tasks other + // environments run for it, so two environments delegating to each other + // never read each other's totals. + const localSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => { let previous = EMPTY_SUBAGENT_REQUESTS; return Atom.make((get) => { const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId))); - if ( - next.size === previous.size && - [...next].every(([threadId, request]) => previous.get(threadId) === request) - ) { - return previous; + if (sameRequests(previous, next)) return previous; + previous = next; + return next; + }).pipe(Atom.withLabel(`environment-local-subagent-requests:${environmentId}`)); + }); + + const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => { + let previous = EMPTY_SUBAGENT_REQUESTS; + return Atom.make((get) => { + const delegated: Array<{ parentThreadId: ThreadId; request: PendingSubagentRequest }> = []; + for (const other of enabledEnvironmentIds(get(input.catalogValueAtom))) { + if (other === environmentId) continue; + for (const thread of get(environmentThreadsAtom(other))) { + if (thread.delegatedFrom?.environmentId !== environmentId) continue; + const own = subagentRequest(thread); + const nested = get(localSubagentRequestsAtom(other)).get(thread.id); + const request = own === "approval" ? own : (nested ?? own); + if (request !== null) { + delegated.push({ parentThreadId: thread.delegatedFrom.threadId, request }); + } + } } + const next = + delegated.length === 0 + ? get(localSubagentRequestsAtom(environmentId)) + : pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)), delegated); + if (sameRequests(previous, next)) return previous; previous = next; return next; }).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`)); @@ -280,30 +341,47 @@ export function createEnvironmentThreadShellAtoms(input: { }); // Child approvals and questions are hidden with their sidebar rows. Read their - // shell summaries, without subscribing to every child transcript. + // shell summaries, without subscribing to every child transcript. A task + // delegated to a linked environment is a child too, with its own subagents. const childThreadInputsAtomFamily = Atom.family((key: string) => { - const ref = parseThreadKey(key); let previous: ReadonlyArray = []; return Atom.make((get) => { - const children = new Map(); - for (const thread of get(environmentThreadsAtom(ref.environmentId))) { - const parent = thread.lineage.parentThreadId; - if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue; - const siblings = children.get(parent); - if (siblings) siblings.push(thread); - else children.set(parent, [thread]); + const children = new Map< + string, + Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }> + >(); + const addChild = ( + parent: ScopedThreadRef, + environmentId: EnvironmentId, + thread: OrchestrationV2ThreadShell, + ) => { + const siblings = children.get(threadKey(parent)); + if (siblings) siblings.push({ environmentId, thread }); + else children.set(threadKey(parent), [{ environmentId, thread }]); + }; + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + for (const thread of get(environmentThreadsAtom(environmentId))) { + const parent = thread.lineage.parentThreadId; + if (parent !== null && thread.lineage.relationshipToParent === "subagent") { + addChild({ environmentId, threadId: parent }, environmentId, thread); + } else if (thread.delegatedFrom !== undefined) { + addChild(thread.delegatedFrom, environmentId, thread); + } + } } - const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId)); - const seen = new Set([ref.threadId]); - const pending = [ref.threadId]; + const seen = new Set([key]); + const pending = [key]; const next: EnvironmentThreadShell[] = []; for (const parent of pending) { - for (const child of children.get(parent) ?? []) { - if (seen.has(child.id)) continue; - seen.add(child.id); - pending.push(child.id); - if (subagentRequest(child) !== null) { - next.push(scopedThread(ref.environmentId, child, subagentRequests)); + for (const { environmentId, thread } of children.get(parent) ?? []) { + const childKey = threadKey({ environmentId, threadId: thread.id }); + if (seen.has(childKey)) continue; + seen.add(childKey); + pending.push(childKey); + if (subagentRequest(thread) !== null) { + next.push( + scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))), + ); } } } @@ -313,6 +391,7 @@ export function createEnvironmentThreadShellAtoms(input: { previous.length === next.length && previous.every( (thread, index) => + thread.environmentId === next[index]?.environmentId && thread.id === next[index]?.id && thread.title === next[index]?.title && thread.hasPendingApprovals === next[index]?.hasPendingApprovals, @@ -402,14 +481,47 @@ export function createEnvironmentThreadShellAtoms(input: { return next; }).pipe(Atom.withLabel("environment-quiet-thread-shell-list")); + let previousDelegatedUnderParent: ReadonlySet = new Set(); + const delegatedUnderParentAtom = Atom.make((get) => { + const environmentIds = new Set(enabledEnvironmentIds(get(input.catalogValueAtom))); + const next = new Set(); + for (const environmentId of environmentIds) { + for (const thread of get(environmentThreadsAtom(environmentId))) { + const parent = thread.delegatedFrom; + if ( + parent !== undefined && + environmentIds.has(parent.environmentId) && + // An archived parent leaves navigation; its task there stays listed on its own. + get(environmentThreadIndexAtom(parent.environmentId)).get(parent.threadId)?.archivedAt === + null + ) { + next.add(threadKey({ environmentId, threadId: thread.id })); + } + } + } + if ( + next.size === previousDelegatedUnderParent.size && + [...next].every((key) => previousDelegatedUnderParent.has(key)) + ) { + return previousDelegatedUnderParent; + } + previousDelegatedUnderParent = next; + return next; + }).pipe(Atom.withLabel("environment-delegated-under-parent")); + let previousNavigationShells: ReadonlyArray = []; const navigationThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; + const underParent = get(delegatedUnderParentAtom); for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); for (const thread of get(environmentThreadsAtom(environmentId))) { - if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent") + if ( + thread.archivedAt !== null || + isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) + ) { continue; + } next.push(scopedThread(environmentId, thread, subagentRequests)); } } @@ -427,6 +539,8 @@ export function createEnvironmentThreadShellAtoms(input: { threadShellsAtom, quietThreadShellsAtom, navigationThreadShellsAtom, + delegatedUnderParentAtom, + pendingSubagentRequestsAtom, threadShellsForProjectRefsAtom: (refs: ReadonlyArray) => threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)), threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)), From fff4c79026f41dc216ba53dcb9f889f107ddccca Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:51:05 -0700 Subject: [PATCH 126/408] fix(server): a remote task with no project there says how to bring one Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 186 ++++---- .../ThreadManagementService.ts | 19 +- apps/server/src/peer/RemoteDelegation.ts | 420 +++++++++--------- 3 files changed, 311 insertions(+), 314 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c1f515df3ca9..1db07b3ca2aa 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1580,113 +1580,111 @@ const make = Effect.gen(function* () { }); /** `mode=wait` on a task already recorded, as `delegateTask` does for its own. */ - const awaitTask = ( + const awaitTask = Effect.fn("OrchestratorMcpService.awaitTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, requestedTimeoutMs: number | undefined, - ): Effect.Effect => - Effect.gen(function* () { - const timeoutMs = Math.min( - MAX_WAIT_TIMEOUT_MS, - Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), - ); - const waited = yield* waitForTask(scope, taskId, timeoutMs); - if (Option.isSome(waited)) return waited.value; - // As for a local task: once the blocking wait ends, a later result wakes the parent. - yield* threadManagement - .dispatch({ - type: "delegated_task.wake-policy", - commandId: stableCommandId({ - scope, - requestKey: taskId, - operation: "delegate-task-wake-policy", - }), - parentThreadId: scope.thread.threadId, - taskId, - completionWake: "always", - }) - .pipe(Effect.ignoreCause({ log: true })); - return yield* readTask(scope, taskId, true, true); - }); + ): Effect.fn.Return { + const timeoutMs = Math.min( + MAX_WAIT_TIMEOUT_MS, + Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + ); + const waited = yield* waitForTask(scope, taskId, timeoutMs); + if (Option.isSome(waited)) return waited.value; + // As for a local task: once the blocking wait ends, a later result wakes the parent. + yield* threadManagement + .dispatch({ + type: "delegated_task.wake-policy", + commandId: stableCommandId({ + scope, + requestKey: taskId, + operation: "delegate-task-wake-policy", + }), + parentThreadId: scope.thread.threadId, + taskId, + completionWake: "always", + }) + .pipe(Effect.ignoreCause({ log: true })); + return yield* readTask(scope, taskId, true, true); + }); /** * A task that runs in a linked environment, answered from its row here: * the follower records its result once its thread there ends. */ - const readRemoteTask = ( + const readRemoteTask = Effect.fn("OrchestratorMcpService.readRemoteTask")(function* ( scope: McpThreadInvocationScope, task: OrchestrationV2Subagent, waitTimedOut: boolean, acknowledgeTerminal: boolean, - ): Effect.Effect => - Effect.gen(function* () { - const status: OrchestratorMcpDelegateTaskResult["status"] = - task.result === null - ? "running" - : task.status === "completed" || - task.status === "failed" || - task.status === "cancelled" || - task.status === "interrupted" - ? task.status - : "completed"; - const terminal = isTerminalTaskStatus(status); - if ( - acknowledgeTerminal && - terminal && - task.completionDelivery?.state !== "acknowledged" && - task.completionDelivery?.state !== "disposed" - ) { - const parentProjection = yield* loadProjection(scope.thread.threadId); - const observingRun = ThreadManagementService.latestActiveRun(parentProjection); - yield* threadManagement - .dispatch({ - type: "delegated_task.completion-delivery.acknowledge", - commandId: stableCommandId({ - scope, - requestKey: yield* requestKey(undefined), - operation: "task-status-acknowledge", - }), - parentThreadId: scope.thread.threadId, - taskId: task.id, - observedByRunId: - observingRun?.providerInstanceId === scope.thread.providerInstanceId - ? observingRun.id - : null, - }) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to acknowledge delegated task ${task.id}: ${errorMessage(error)}`, - ), + ): Effect.fn.Return { + const status: OrchestratorMcpDelegateTaskResult["status"] = + task.result === null + ? "running" + : task.status === "completed" || + task.status === "failed" || + task.status === "cancelled" || + task.status === "interrupted" + ? task.status + : "completed"; + const terminal = isTerminalTaskStatus(status); + if ( + acknowledgeTerminal && + terminal && + task.completionDelivery?.state !== "acknowledged" && + task.completionDelivery?.state !== "disposed" + ) { + const parentProjection = yield* loadProjection(scope.thread.threadId); + const observingRun = ThreadManagementService.latestActiveRun(parentProjection); + yield* threadManagement + .dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: stableCommandId({ + scope, + requestKey: yield* requestKey(undefined), + operation: "task-status-acknowledge", + }), + parentThreadId: scope.thread.threadId, + taskId: task.id, + observedByRunId: + observingRun?.providerInstanceId === scope.thread.providerInstanceId + ? observingRun.id + : null, + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to acknowledge delegated task ${task.id}: ${errorMessage(error)}`, ), - ); - } - return { - taskId: task.id, - childThreadId: null, - ...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }), - childRunId: null, - childNodeId: task.id, - status, - workState: terminal ? "result_available" : "working", - hasPendingChildRuns: false, - providerInstanceId: task.providerInstanceId, - model: task.model, - summary: task.result, - resultContextTransferId: null, - latestTerminalRunId: null, - latestTerminalStatus: terminal - ? (status as OrchestratorMcpDelegateTaskResult["latestTerminalStatus"]) - : null, - latestTerminalSummary: terminal ? task.result : null, - latestTerminalResultContextTransferId: null, - // Its questions and approvals are answered in the environment it runs in. - hasPendingQuestion: false, - pendingApproval: null, - waitTimedOut, - } satisfies OrchestratorMcpDelegateTaskResult; - }); + ), + ); + } + return { + taskId: task.id, + childThreadId: null, + ...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }), + childRunId: null, + childNodeId: task.id, + status, + workState: terminal ? "result_available" : "working", + hasPendingChildRuns: false, + providerInstanceId: task.providerInstanceId, + model: task.model, + summary: task.result, + resultContextTransferId: null, + latestTerminalRunId: null, + latestTerminalStatus: terminal + ? (status as OrchestratorMcpDelegateTaskResult["latestTerminalStatus"]) + : null, + latestTerminalSummary: terminal ? task.result : null, + latestTerminalResultContextTransferId: null, + // Its questions and approvals are answered in the environment it runs in. + hasPendingQuestion: false, + pendingApproval: null, + waitTimedOut, + } satisfies OrchestratorMcpDelegateTaskResult; + }); const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")( function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 81b410a46e74..3712a1374a99 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -906,15 +906,16 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(loadError)); return pending ? undefined : progress.resultRun; }); - const evaluate = (runs: ReadonlyArray) => - Effect.gen(function* () { - const current = yield* outcome(runs); - if (!current.settled || !untilDelegatedWorkSettled) { - return { ...current, resultRun: undefined }; - } - const resultRun = yield* delegatedWorkResult; - return { ...current, settled: resultRun !== undefined, resultRun }; - }); + const evaluate = Effect.fn("orchestrationV2.threadManagement.evaluate")(function* ( + runs: ReadonlyArray, + ) { + const current = yield* outcome(runs); + if (!current.settled || !untilDelegatedWorkSettled) { + return { ...current, resultRun: undefined }; + } + const resultRun = yield* delegatedWorkResult; + return { ...current, settled: resultRun !== undefined, resultRun }; + }); const settledResult = (current: Effect.Success>) => ({ threadId: input.threadId, run: current.run, diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 3f8d6beb2c91..647d28a3dad8 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -121,55 +121,54 @@ const make = Effect.gen(function* () { const followers = yield* Scope.Scope; /** The peer's project with this thread's repository, or the one the caller named. */ - const resolveRemoteProject = ( + const resolveRemoteProject = Effect.fn("RemoteDelegation.resolveRemoteProject")(function* ( scope: ThreadScope, environmentId: EnvironmentId, parentProjectId: ProjectId, requested: ProjectId | undefined, - ) => - Effect.gen(function* () { - if (requested !== undefined) return requested; - const here = yield* projects.getById(parentProjectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.orElseSucceed(() => undefined), - ); - // The project's own identity is a one-minute cache that reads blank when - // cold, so resolve it here, as the other side's t3_project_list does. - const key = - here === undefined - ? undefined - : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey; - if (key === undefined) { - return yield* new OrchestratorMcpFailure({ - code: "target_required", - message: "Pass target.projectId: this thread's project has no repository to match there.", - }); - } - const matches: Array<{ readonly id: ProjectId; readonly title: string }> = []; - let cursor: number | null = 0; - while (cursor !== null) { - const listed: Tool.Success = - yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, { - cursor, - limit: 100, - }); - matches.push( - ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key), - ); - cursor = listed.nextCursor; - } - if (matches.length === 1) return matches[0]!.id; + ) { + if (requested !== undefined) return requested; + const here = yield* projects.getById(parentProjectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + // The project's own identity is a one-minute cache that reads blank when + // cold, so resolve it here, as the other side's t3_project_list does. + const key = + here === undefined + ? undefined + : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey; + if (key === undefined) { return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - matches.length === 0 - ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them.` - : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`, + code: "target_required", + message: "Pass target.projectId: this thread's project has no repository to match there.", }); + } + const matches: Array<{ readonly id: ProjectId; readonly title: string }> = []; + let cursor: number | null = 0; + while (cursor !== null) { + const listed: Tool.Success = + yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, { + cursor, + limit: 100, + }); + matches.push( + ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key), + ); + cursor = listed.nextCursor; + } + if (matches.length === 1) return matches[0]!.id; + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + matches.length === 0 + ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them. To bring the repository there, use t3_project_clone and then t3_project_create with this environmentId.` + : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`, }); + }); - const delegate: RemoteDelegation["Service"]["delegate"] = (scope, input) => - Effect.gen(function* () { + const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")( + function* (scope, input) { const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe( Effect.mapError( () => @@ -336,7 +335,8 @@ const make = Effect.gen(function* () { } yield* followOne(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers)); return { taskId }; - }); + }, + ); /** * Completes `task` here with its thread there's final state. Each attempt @@ -345,41 +345,40 @@ const make = Effect.gen(function* () { * or an earlier report) is done. `stoppedThere` records that nothing is * left to stop there, also on a task that already has its result. */ - const complete = ( + const complete = Effect.fn("RemoteDelegation.complete")(function* ( parentThreadId: ThreadId, taskId: NodeId, status: "completed" | "failed" | "cancelled" | "interrupted", result: string, stoppedThere: "ran-out" | "stopped" | undefined, stopCount?: number, - ) => - Effect.gen(function* () { - const attempt = yield* crypto.randomUUIDv4().pipe(Effect.orDie); - yield* threads - .dispatch({ - type: "delegated_task.remote.complete", - commandId: CommandId.make(`command:remote-task-complete:${taskId}:${attempt}`), - parentThreadId, - taskId, - status, - result, - ...(stoppedThere === undefined ? {} : { stoppedThere }), - ...(stopCount === undefined ? {} : { stopCount }), - }) - .pipe( - Effect.catch((error) => - threads - .getThreadRecords(parentThreadId, ["subagents"]) - .pipe( - Effect.flatMap(({ subagents }) => - subagents.find((task) => task.id === taskId)?.result != null - ? Effect.void - : Effect.fail(error), - ), + ) { + const attempt = yield* crypto.randomUUIDv4().pipe(Effect.orDie); + yield* threads + .dispatch({ + type: "delegated_task.remote.complete", + commandId: CommandId.make(`command:remote-task-complete:${taskId}:${attempt}`), + parentThreadId, + taskId, + status, + result, + ...(stoppedThere === undefined ? {} : { stoppedThere }), + ...(stopCount === undefined ? {} : { stopCount }), + }) + .pipe( + Effect.catch((error) => + threads + .getThreadRecords(parentThreadId, ["subagents"]) + .pipe( + Effect.flatMap(({ subagents }) => + subagents.find((task) => task.id === taskId)?.result != null + ? Effect.void + : Effect.fail(error), ), - ), - ); - }); + ), + ), + ); + }); /** * How this environment reaches a task's thread there: as the parent @@ -429,62 +428,61 @@ const make = Effect.gen(function* () { * result, read whole however long it is. A failed run prefers its error * from the activity view over an earlier reply, without taking another run's. */ - const lastReply = ( + const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* ( scope: ThreadScope, remote: OrchestrationV2RemoteTaskChild, runId: RunId | null, failed = false, - ) => - Effect.gen(function* () { - let reply: OrchestratorMcpThreadTimelineItem | undefined; - let error: OrchestratorMcpThreadTimelineItem | undefined; - let afterPosition: number | undefined; - while (true) { - const read = yield* forwarding.readThread(scope, remote.environmentId, { - threadId: remote.threadId, - view: failed ? "activity" : "messages", - limit: 100, - ...(afterPosition === undefined ? {} : { afterPosition }), - }); - reply = + ) { + let reply: OrchestratorMcpThreadTimelineItem | undefined; + let error: OrchestratorMcpThreadTimelineItem | undefined; + let afterPosition: number | undefined; + while (true) { + const read = yield* forwarding.readThread(scope, remote.environmentId, { + threadId: remote.threadId, + view: failed ? "activity" : "messages", + limit: 100, + ...(afterPosition === undefined ? {} : { afterPosition }), + }); + reply = + read.items.findLast( + (item) => item.type === "assistant_message" && (runId === null || item.runId === runId), + ) ?? reply; + if (failed) { + error = read.items.findLast( - (item) => item.type === "assistant_message" && (runId === null || item.runId === runId), - ) ?? reply; - if (failed) { - error = - read.items.findLast( - (item) => item.type === "error" && (runId === null || item.runId === runId), - ) ?? error; - } - if (!read.hasMore || read.nextPosition === null) break; - afterPosition = read.nextPosition; - } - reply = error ?? reply; - if (reply === undefined) return undefined; - let text = reply.text ?? ""; - let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null; - while (textOffset !== null) { - const rest = yield* forwarding.readThread(scope, remote.environmentId, { - threadId: remote.threadId, - itemId: reply.itemId, - textOffset, - maxCharsPerItem: 50_000, - }); - const part = rest.items[0]; - if (part === undefined) break; - text += part.text ?? ""; - textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; + (item) => item.type === "error" && (runId === null || item.runId === runId), + ) ?? error; } - return text; - }); + if (!read.hasMore || read.nextPosition === null) break; + afterPosition = read.nextPosition; + } + reply = error ?? reply; + if (reply === undefined) return undefined; + let text = reply.text ?? ""; + let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null; + while (textOffset !== null) { + const rest = yield* forwarding.readThread(scope, remote.environmentId, { + threadId: remote.threadId, + itemId: reply.itemId, + textOffset, + maxCharsPerItem: 50_000, + }); + const part = rest.items[0]; + if (part === undefined) break; + text += part.text ?? ""; + textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; + } + return text; + }); /** * Why following a task can never succeed, if that is what `error` means. * The far side's message already says what was refused and what to do; a * link forgotten here only reads as a bad request, so it is named. */ - const finalReason = (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) => - Effect.gen(function* () { + const finalReason = Effect.fn("RemoteDelegation.finalReason")( + function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) { if (isFinal(error)) return error.message; if (error.code !== "invalid_request") return undefined; const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); @@ -493,7 +491,9 @@ const make = Effect.gen(function* () { if (environmentId === undefined) return error.message; const link = yield* links.get(environmentId); return Option.isSome(link) ? undefined : error.message; - }).pipe(Effect.orElseSucceed(() => undefined)); + }, + Effect.orElseSucceed(() => undefined), + ); /** A task's thread there that ended without a reply. */ const noReply = "(The thread in the linked environment ended without a reply.)"; @@ -529,114 +529,111 @@ const make = Effect.gen(function* () { * A task completed here first (cancelled, or its parent stopped) is * stopped there, and done once that stop is recorded here. */ - const followOnce = (parentThreadId: ThreadId, taskId: NodeId) => - Effect.gen(function* () { - const sequence = yield* threads.getThreadEventSequence(parentThreadId); - const records = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); - const task = records.subagents.find((candidate) => candidate.id === taskId); - if (task?.remoteChild === undefined) return true; - const remote = task.remoteChild; - const scope = followScope( - { threadId: parentThreadId, providerInstanceId: records.thread.providerInstanceId }, - remote, - ); - // Ended here, maybe while this follower backed off from an unreachable - // machine or before a restart: it still has to be stopped there. So - // does one its parent here was stopped after, for what followed there. - if (task.result !== null) { - if ( - remote.stoppedThere === false || - ((task.status === "cancelled" || task.status === "interrupted") && - remote.stoppedThere !== true) - ) { - const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`; - yield* stopThere(scope, remote, key).pipe( - // Its thread there now runs above what this side may touch, say - // because the parent here was lowered since; no retry changes that. - Effect.catchIf(isModeRefusal, (error) => - Effect.logWarning("A linked environment refused to stop a delegated task", { - taskId, - reason: error.message, - }), - ), - ); - yield* complete( - parentThreadId, - taskId, - terminalStatus(task.status), - task.result, - "stopped", - remote.stopCount, - ); - return yield* settled(parentThreadId, taskId); - } - return true; - } - const endedHere = threads - .streamStoredEventsFrom({ - threadId: parentThreadId, - afterSequence: sequence, - eventType: "subagent.updated", - }) - .pipe( - Stream.filter( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.id === taskId && - stored.event.payload.result !== null, - ), - Stream.runHead, - Effect.flatMap((ended) => - Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never, + const followOnce = Effect.fn("RemoteDelegation.followOnce")(function* ( + parentThreadId: ThreadId, + taskId: NodeId, + ) { + const sequence = yield* threads.getThreadEventSequence(parentThreadId); + const records = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); + const task = records.subagents.find((candidate) => candidate.id === taskId); + if (task?.remoteChild === undefined) return true; + const remote = task.remoteChild; + const scope = followScope( + { threadId: parentThreadId, providerInstanceId: records.thread.providerInstanceId }, + remote, + ); + // Ended here, maybe while this follower backed off from an unreachable + // machine or before a restart: it still has to be stopped there. So + // does one its parent here was stopped after, for what followed there. + if (task.result !== null) { + if ( + remote.stoppedThere === false || + ((task.status === "cancelled" || task.status === "interrupted") && + remote.stoppedThere !== true) + ) { + const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`; + yield* stopThere(scope, remote, key).pipe( + // Its thread there now runs above what this side may touch, say + // because the parent here was lowered since; no retry changes that. + Effect.catchIf(isModeRefusal, (error) => + Effect.logWarning("A linked environment refused to stop a delegated task", { + taskId, + reason: error.message, + }), ), ); - const waited = yield* forwarding - .waitForThread(scope, remote.environmentId, { - threadId: remote.threadId, - ...(remote.runId === undefined ? {} : { runId: remote.runId }), - timeoutMs: FOLLOW_WAIT_MS, - // A thread there whose run ended may still be waiting on its own - // tasks to wake it for the answer, which a task here waits for too. - // An older peer ignores this and reports the run alone. - untilDelegatedWorkSettled: true, - }) - .pipe(Effect.raceFirst(endedHere)); - // The next look reads the result and stops it there. - if ("endedHere" in waited) return false; - if (waited.timedOut) return false; - // A task recorded without its run waits on the thread's latest; a - // thread there with none has nothing left to wait for. - if (waited.runId === null) { - const reply = yield* lastReply(scope, remote, null); yield* complete( parentThreadId, taskId, - reply === undefined ? "failed" : "completed", - reply ?? "The thread in the linked environment has no run to follow.", - "ran-out", + terminalStatus(task.status), + task.result, + "stopped", + remote.stopCount, ); return yield* settled(parentThreadId, taskId); } - if (!isTerminal(waited.status)) return false; - const resultRun = waited.resultRun ?? { - runId: remote.runId ?? waited.runId, - status: waited.status, - }; - const result = yield* lastReply( - scope, - remote, - resultRun.runId, - resultRun.status === "failed", + return true; + } + const endedHere = threads + .streamStoredEventsFrom({ + threadId: parentThreadId, + afterSequence: sequence, + eventType: "subagent.updated", + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === taskId && + stored.event.payload.result !== null, + ), + Stream.runHead, + Effect.flatMap((ended) => + Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never, + ), ); + const waited = yield* forwarding + .waitForThread(scope, remote.environmentId, { + threadId: remote.threadId, + ...(remote.runId === undefined ? {} : { runId: remote.runId }), + timeoutMs: FOLLOW_WAIT_MS, + // A thread there whose run ended may still be waiting on its own + // tasks to wake it for the answer, which a task here waits for too. + // An older peer ignores this and reports the run alone. + untilDelegatedWorkSettled: true, + }) + .pipe(Effect.raceFirst(endedHere)); + // The next look reads the result and stops it there. + if ("endedHere" in waited) return false; + if (waited.timedOut) return false; + // A task recorded without its run waits on the thread's latest; a + // thread there with none has nothing left to wait for. + if (waited.runId === null) { + const reply = yield* lastReply(scope, remote, null); yield* complete( parentThreadId, taskId, - terminalStatus(resultRun.status), - result ?? noReply, + reply === undefined ? "failed" : "completed", + reply ?? "The thread in the linked environment has no run to follow.", "ran-out", ); return yield* settled(parentThreadId, taskId); - }); + } + if (!isTerminal(waited.status)) return false; + const resultRun = waited.resultRun ?? { + runId: remote.runId ?? waited.runId, + status: waited.status, + }; + const result = yield* lastReply(scope, remote, resultRun.runId, resultRun.status === "failed"); + yield* complete( + parentThreadId, + taskId, + terminalStatus(resultRun.status), + result ?? noReply, + "ran-out", + ); + return yield* settled(parentThreadId, taskId); + }); /** * Whether the task is done here after the follower reported its run ran @@ -690,8 +687,8 @@ const make = Effect.gen(function* () { ); }); - const cancel: RemoteDelegation["Service"]["cancel"] = (scope, task, input) => - Effect.gen(function* () { + const cancel: RemoteDelegation["Service"]["cancel"] = Effect.fn("RemoteDelegation.cancel")( + function* (scope, task, input) { const remote = task.remoteChild; if (remote === undefined) { return yield* new OrchestratorMcpFailure({ @@ -760,7 +757,8 @@ const make = Effect.gen(function* () { taskId: task.id, status: "cancel_requested", } satisfies OrchestratorMcpTaskCancelResult; - }); + }, + ); const start: RemoteDelegation["Service"]["start"] = () => forkParked( From 70a2a7bdd25d1c3729a864517727914fc3b01d2b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 20:39:21 -0700 Subject: [PATCH 127/408] fix(server): remote task followers read only their own task RemoteDelegation.start resumes every open remote task at once, and each follower read its parent's whole subagent list to find one task, then held it across a wait of up to ten minutes. A parent with 1,441 tasks (35 MB of payload) and 122 open ones made every restart decode ~170k records and hold 8 GB, so the server ran out of heap seconds after starting and crash-looped. getThreadRecords now takes a subagentIds filter. Followers, and task_status waits that re-read on every parent subagent.updated, read just their task. Against a copy of the affected database the startup fan-out drops from 8.2 GB retained over 21.6 s to 8 MB over 61 ms. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 18 ++++++- .../orchestration-v2/ProjectionStore.test.ts | 51 +++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 9 +++- apps/server/src/peer/RemoteDelegation.ts | 46 ++++++++--------- 4 files changed, 97 insertions(+), 27 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 1db07b3ca2aa..e2d3676034fb 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1023,6 +1023,22 @@ const make = Effect.gen(function* () { ), ); + // Task waits read on every wake of a parent that may hold thousands of + // tasks, so they read only the task they watch and what its status needs. + const loadTaskParent = (threadId: ThreadId, taskId: NodeId) => + threadManagement + .getThreadRecords(threadId, ["runs", "subagents", "contextTransfers"], { + subagentIds: [taskId], + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to read thread ${threadId}: ${errorMessage(error)}`, + ), + ), + ); + const loadProjectThread = ( projectId: OrchestrationV2ThreadProjection["thread"]["projectId"], threadId: ThreadId, @@ -1388,7 +1404,7 @@ const make = Effect.gen(function* () { acknowledgementOperation = "task-status-acknowledge", ): Effect.fn.Return { yield* requireCapability(scope); - const parentProjection = yield* loadProjection(scope.thread.threadId); + const parentProjection = yield* loadTaskParent(scope.thread.threadId, taskId); const task = parentProjection.subagents.find( (candidate) => candidate.id === taskId && diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 83f33269f399..b60a8a6cdce1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -964,6 +964,56 @@ const runlessNativeSubagentNeedsRecovery = Effect.gen(function* () { } }); +const subagentRecordsSelectById = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("subagent-records-by-id"); + const now = yield* DateTime.now; + const ids = [NodeId.make("node:subagent-by-id:a"), NodeId.make("node:subagent-by-id:b")]; + for (const id of ids) { + yield* store.apply({ + id: EventId.make(`event:${id}`), + type: "subagent.updated", + threadId, + nodeId: id, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id, + threadId, + runId: null, + parentNodeId: NodeId.make("node:subagent-by-id:parent"), + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Do the work", + title: "Delegated task", + model: null, + status: "running", + result: null, + startedAt: now, + completedAt: null, + updatedAt: now, + }, + }); + } + const read = (subagentIds?: ReadonlyArray) => + store + .getThreadRecords(threadId, ["subagents"], subagentIds === undefined ? {} : { subagentIds }) + .pipe(Effect.map(({ subagents }) => subagents.map((task) => task.id))); + assert.deepEqual(yield* read(), ids); + assert.deepEqual(yield* read([ids[1]!]), [ids[1]]); + assert.deepEqual(yield* read([]), []); +}); + +it.effect("memory record reads select subagents by id", () => + subagentRecordsSelectById.pipe(Effect.provide(ProjectionStore.layerMemory)), +); + const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(function* ( suffix: string, ) { @@ -1179,6 +1229,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { assert.deepEqual(recovery?.restartCancelledBackgroundWork, work); }), ); + it.effect("record reads select subagents by id", () => subagentRecordsSelectById); it.effect( "command reads skip finished leaf nodes of finished runs", () => commandReadsSkipSettledLeafNodes, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 49aef518a8ed..9a9883428bfa 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -323,6 +323,7 @@ export interface ProjectionRecordFilter { readonly messageRunIds?: ReadonlyArray; readonly turnItemRunIds?: ReadonlyArray; readonly runIds?: ReadonlyArray; + readonly subagentIds?: ReadonlyArray; readonly turnItemTypes?: ReadonlyArray; readonly turnItemStatuses?: ReadonlyArray; readonly omitSettledLeafNodes?: boolean; @@ -3270,13 +3271,15 @@ export const layer: Layer.Layer = rows.toSorted((left, right) => left.position - right.position), ), ), - fields !== undefined && !fields.includes("subagents") + (fields !== undefined && !fields.includes("subagents")) || + (window === undefined && matchesNothing(filter?.subagentIds)) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId} + ${filter?.subagentIds === undefined ? sql`` : sql`AND subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentIds)}))`} ORDER BY COALESCE(started_at, ''), subagent_id ASC ` : sql` @@ -6891,6 +6894,10 @@ export const layerMemory: Layer.Layer = Layer.effect( filter?.runIds === undefined ? projection.runs : projection.runs.filter((row) => filter.runIds!.includes(row.id)), + subagents: + filter?.subagentIds === undefined + ? projection.subagents + : projection.subagents.filter((row) => filter.subagentIds!.includes(row.id)), turnItems: projection.turnItems.filter( (row) => (filter?.turnItemRunIds === undefined || diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 647d28a3dad8..3acfe1b374b9 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -120,6 +120,15 @@ const make = Effect.gen(function* () { // Followers live as long as this service, so shutting down stops them. const followers = yield* Scope.Scope; + // One follower runs per open task and holds what it read across a wait of + // up to FOLLOW_WAIT_MS, so it reads its own task, never the parent's whole + // task list: a parent with thousands of tasks made every restart decode + // that list once per open task at the same time and ran out of heap. + const readTask = (parentThreadId: ThreadId, taskId: NodeId) => + threads + .getThreadRecords(parentThreadId, ["subagents"], { subagentIds: [taskId] }) + .pipe(Effect.map(({ thread, subagents }) => ({ thread, task: subagents[0] }))); + /** The peer's project with this thread's repository, or the one the caller named. */ const resolveRemoteProject = Effect.fn("RemoteDelegation.resolveRemoteProject")(function* ( scope: ThreadScope, @@ -367,15 +376,9 @@ const make = Effect.gen(function* () { }) .pipe( Effect.catch((error) => - threads - .getThreadRecords(parentThreadId, ["subagents"]) - .pipe( - Effect.flatMap(({ subagents }) => - subagents.find((task) => task.id === taskId)?.result != null - ? Effect.void - : Effect.fail(error), - ), - ), + readTask(parentThreadId, taskId).pipe( + Effect.flatMap(({ task }) => (task?.result != null ? Effect.void : Effect.fail(error))), + ), ), ); }); @@ -485,9 +488,8 @@ const make = Effect.gen(function* () { function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) { if (isFinal(error)) return error.message; if (error.code !== "invalid_request") return undefined; - const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); - const environmentId = subagents.find((task) => task.id === taskId)?.remoteChild - ?.environmentId; + const { task } = yield* readTask(parentThreadId, taskId); + const environmentId = task?.remoteChild?.environmentId; if (environmentId === undefined) return error.message; const link = yield* links.get(environmentId); return Option.isSome(link) ? undefined : error.message; @@ -515,8 +517,8 @@ const make = Effect.gen(function* () { const reason = yield* finalReason(parentThreadId, taskId, error); if (reason === undefined) return yield* error; // Gone there, or no link to reach it by: nothing left to stop there. - const { subagents } = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); - const stopCount = subagents.find((task) => task.id === taskId)?.remoteChild?.stopCount; + const { task } = yield* readTask(parentThreadId, taskId); + const stopCount = task?.remoteChild?.stopCount; yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount); }), }), @@ -534,12 +536,11 @@ const make = Effect.gen(function* () { taskId: NodeId, ) { const sequence = yield* threads.getThreadEventSequence(parentThreadId); - const records = yield* threads.getThreadRecords(parentThreadId, ["subagents"]); - const task = records.subagents.find((candidate) => candidate.id === taskId); + const { thread, task } = yield* readTask(parentThreadId, taskId); if (task?.remoteChild === undefined) return true; const remote = task.remoteChild; const scope = followScope( - { threadId: parentThreadId, providerInstanceId: records.thread.providerInstanceId }, + { threadId: parentThreadId, providerInstanceId: thread.providerInstanceId }, remote, ); // Ended here, maybe while this follower backed off from an unreachable @@ -642,14 +643,9 @@ const make = Effect.gen(function* () { * the next look sends it. */ const settled = (parentThreadId: ThreadId, taskId: NodeId) => - threads - .getThreadRecords(parentThreadId, ["subagents"]) - .pipe( - Effect.map( - ({ subagents }) => - subagents.find((task) => task.id === taskId)?.remoteChild?.stoppedThere === true, - ), - ); + readTask(parentThreadId, taskId).pipe( + Effect.map(({ task }) => task?.remoteChild?.stoppedThere === true), + ); const following = new Map(); From e692add9ee5a35d967da18fc548155c47bc21eb2 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:01:05 -0700 Subject: [PATCH 128/408] feat(server,web,mobile): an agent sets up a link to another environment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A user asks an agent to "delegate this to my vps" without knowing any address, so t3_environment_link needs none. The agent passes a hint from the user's words, an environmentId when it knows the machine, or an address only when the user gave one. The tool records a card in the thread and returns pending at once, so no provider's tool-call timeout can close it. A machine already linked here returns linked at once, with no card. The card lets the user pick the machine from the ones their app knows (preselected by the hint; "Another address…" for one it does not), and the access (default supervised, or the agent's suggestion). The client answers with every address it knows for that machine and a one-use pairing code, minted there with the user's own session when it can, or pasted. The server links through the first address that answers as that machine, never sends the code to one that answers as another, and keeps only the matching addresses. A machine already linked is answered with "Use this link". The answer reaches the agent as a notification in its thread: linked (with the environment id, label and the access chosen), declined, or failed with the reason. The pairing code is never recorded. Stopping or archiving the thread closes a pending card; a retry with the same clientRequestId returns the card's current outcome. t3_environment_unlink undoes a link. Both tools need a full-access caller and are refused for linked work. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/features/threads/LinkRequestCard.tsx | 508 +++++++++++++ .../src/features/threads/ThreadFeed.tsx | 12 + apps/mobile/src/lib/threadActivity.ts | 14 +- apps/mobile/src/state/peerLinks.ts | 35 + apps/mobile/src/state/peerPairingCode.ts | 42 ++ apps/server/src/mcp/OrchestratorMcpService.ts | 4 + ...OrchestratorMcpToolkit.integration.test.ts | 4 + apps/server/src/mcp/linkOrigin.test.ts | 4 + apps/server/src/mcp/toolkits/core.test.ts | 12 + .../src/mcp/toolkits/orchestrator/handlers.ts | 25 + .../src/mcp/toolkits/orchestrator/tools.ts | 42 +- .../src/observability/RpcInstrumentation.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 170 +++++ .../src/orchestration-v2/ProjectionStore.ts | 7 +- .../ProviderRuntimeRecoveryService.test.ts | 83 +++ .../ProviderRuntimeRecoveryService.ts | 2 + apps/server/src/peer/PeerForwarding.test.ts | 22 +- apps/server/src/peer/PeerForwarding.ts | 121 +-- apps/server/src/peer/PeerLinkRequests.test.ts | 705 ++++++++++++++++++ apps/server/src/peer/PeerLinkRequests.ts | 402 ++++++++++ apps/server/src/peer/PeerLinks.test.ts | 69 ++ apps/server/src/peer/PeerLinks.ts | 280 ++++--- apps/server/src/peer/RemoteDelegation.test.ts | 4 + apps/server/src/server.ts | 3 + apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 8 + .../components/auth/ConnectAgentSurface.tsx | 2 +- .../src/components/chat/LinkRequestCard.tsx | 514 +++++++++++++ .../components/chat/TimelineV2EventRow.tsx | 10 + .../components/settings/LinkAccessPicker.tsx | 63 ++ .../settings/LinkedEnvironmentsSettings.tsx | 28 +- apps/web/src/session-logic.ts | 2 + apps/web/src/state/peerLinks.ts | 30 +- apps/web/src/state/peerPairingCode.ts | 42 ++ docs/user/remote-access.md | 7 + packages/client-runtime/package.json | 8 + .../client-runtime/src/linkRequest.test.ts | 255 +++++++ packages/client-runtime/src/linkRequest.ts | 249 +++++++ .../src/state/commandPermissions.test.ts | 24 + .../src/state/peerPairingCode.ts | 75 ++ packages/client-runtime/src/state/server.ts | 10 + packages/client-runtime/src/t3ToolSummary.ts | 10 + .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/orchestrationV2.ts | 75 ++ packages/contracts/src/orchestratorMcp.ts | 75 ++ packages/contracts/src/peerLink.ts | 66 +- packages/contracts/src/rpc.ts | 9 + .../src/server/orchestrationInstructions.ts | 1 + packages/shared/src/t3McpToolPresentation.ts | 10 + 49 files changed, 3952 insertions(+), 196 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkRequestCard.tsx create mode 100644 apps/mobile/src/state/peerPairingCode.ts create mode 100644 apps/server/src/peer/PeerLinkRequests.test.ts create mode 100644 apps/server/src/peer/PeerLinkRequests.ts create mode 100644 apps/web/src/components/chat/LinkRequestCard.tsx create mode 100644 apps/web/src/components/settings/LinkAccessPicker.tsx create mode 100644 apps/web/src/state/peerPairingCode.ts create mode 100644 packages/client-runtime/src/linkRequest.test.ts create mode 100644 packages/client-runtime/src/linkRequest.ts create mode 100644 packages/client-runtime/src/state/peerPairingCode.ts diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx new file mode 100644 index 000000000000..5847e94a9e6f --- /dev/null +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -0,0 +1,508 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type LinkableMachine, + linkRequestAnswerInput, + linkRequestDefaultAccess, + linkRequestDisplay, + linkRequestFailureMessage, + linkRequestInitialMachine, + type LinkRequestItem, + linkRequestTargetName, + rankMachinesByHint, +} from "@t3tools/client-runtime/link-request"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + AuthAccessWriteScope, + type AuthMcpClientAccess, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { useMemo, useRef, useState } from "react"; +import { Modal, Platform, Pressable, ScrollView, View, type ColorValue } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; +import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; +import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; +import { useLinkableMachines } from "../../state/peerLinks"; +import { mintPairingCodeOn } from "../../state/peerPairingCode"; +import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { SettingsChoiceRow } from "../settings/components/SettingsChoiceRow"; +import { SettingsSection } from "../settings/components/SettingsSection"; +import { Button } from "../../components/ui/Button"; +import { RUNTIME_MODE_CHOICES } from "./thread-settings-options"; + +/** The same five levels as web's access picker: read-only, then the runtime modes. */ +const ACCESS_CHOICES: ReadonlyArray<{ + readonly access: AuthMcpClientAccess; + readonly label: string; + readonly description: string; +}> = [ + { + access: "read-only", + label: "Read only", + description: "Read projects and threads. Cannot start, message or change anything.", + }, + ...RUNTIME_MODE_CHOICES.map((choice) => ({ ...choice, access: choice.mode })), +]; +const accessLabel = (access: AuthMcpClientAccess) => + ACCESS_CHOICES.find((choice) => choice.access === access)?.label ?? access; + +const LINK_SYMBOL: AppSymbolName = { ios: "link", android: "desktop_windows" }; + +/** The machine list's row for linking by an address typed in. */ +const ANOTHER_ADDRESS = "another-address"; + +/** Whether the agent left the machine for the user to pick. */ +const picksMachine = (item: LinkRequestItem) => + item.environmentId === undefined && item.url === undefined; + +/** + * Feed card for a link an agent asked the user to make. The user picks the + * access in a sheet; the pairing code lives only in that sheet's state and + * the RPC payload, and is never logged, alerted, or persisted. + */ +export function LinkRequestCard(props: { + readonly environmentId: EnvironmentId; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + readonly iconColor: ColorValue; +}) { + const { item, visibility } = props.projectedItem; + if (item.type !== "link_request") return null; + const display = linkRequestDisplay(item, visibility, accessLabel); + if (display.kind === "pending") { + return ; + } + const icon: AppSymbolName = + display.kind === "pending-elsewhere" + ? LINK_SYMBOL + : display.outcome === "linked" + ? "checkmark" + : display.outcome === "failed" + ? "xmark" + : "minus"; + return ( + + + + {display.label} + + + ); +} + +function PendingLinkRequest(props: { + readonly environmentId: EnvironmentId; + readonly item: LinkRequestItem; +}) { + const { item } = props; + const [open, setOpen] = useState(false); + const [declining, setDeclining] = useState(false); + const [error, setError] = useState(null); + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, { + label: "decline link request", + reportFailure: false, + reportDefect: false, + }); + const canAnswer = useAtomValue( + serverEnvironment.answerLinkRequest.permissionAtom(props.environmentId), + ); + const target = linkRequestTargetName(item); + + const decline = async () => { + const input = linkRequestAnswerInput(item, { type: "decline" }); + if (input === null) return; + setDeclining(true); + setError(null); + const result = await answer({ environmentId: props.environmentId, input }).finally(() => + setDeclining(false), + ); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + } + }; + + return ( + + + + {picksMachine(item) + ? "Link a machine to this environment" + : `Link ${target} to this environment`} + + {item.reason.trim() ? ( + {item.reason} + ) : null} + {item.label !== undefined && item.url !== undefined ? ( + + {item.url} + + ) : null} + + {error !== null ? ( + + {error} + + ) : null} + {canAnswer ? ( + <> + + +
    + ) : ( +

    + Only a session that manages access here can answer this. +

    + )} + +
    + ); +} + +/** + * What the dialog links: a machine from the client's catalog, or an address. + * `urls` is empty when the client knows no direct address for the machine, + * so the user types one. + */ +type DialogTarget = + | { readonly kind: "none" } + | { + readonly kind: "machine"; + readonly environmentId: EnvironmentId; + readonly label: string; + readonly urls: ReadonlyArray; + readonly linked: boolean; + } + | { readonly kind: "address" }; + +function resolveTarget( + item: LinkRequestItem, + machines: ReadonlyArray, + choice: string | null, +): DialogTarget { + if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" }; + const chosen = item.environmentId ?? choice; + if (chosen === null) return { kind: "none" }; + if (chosen === ANOTHER_ADDRESS) return { kind: "address" }; + const machine = machines.find((candidate) => candidate.environmentId === chosen); + return { + kind: "machine", + environmentId: machine?.environmentId ?? (chosen as EnvironmentId), + label: machine?.label ?? linkRequestTargetName(item), + urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])], + linked: machine?.linked ?? false, + }; +} + +/** The dialog's steps: where to link, then what agents may do there. */ +type LinkStep = "machine" | "access"; + +function LinkRequestDialog(props: { + readonly environmentId: EnvironmentId; + readonly item: LinkRequestItem; + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; +}) { + const { item } = props; + const formId = useId(); + const pickMachine = picksMachine(item); + const listed = useLinkableMachines(props.environmentId, props.open); + const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]); + // Null until the user picks; until then the hint's best match is picked. + const [choice, setChoice] = useState(null); + const [address, setAddress] = useState(item.url ?? ""); + const [access, setAccess] = useState(() => linkRequestDefaultAccess(item)); + const [pairingCode, setPairingCode] = useState(""); + const [step, setStep] = useState("machine"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + // Machines whose minting already failed, so the dialog asks for a code instead. + const [mintFailed, setMintFailed] = useState>(new Set()); + // Enter then a click can both run before a re-render; this guard is synchronous. + const inFlight = useRef(false); + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, { + label: "answer link request", + // The failure cause holds the request, and with it the code; keep it out of the console. + reportFailure: false, + reportDefect: false, + }); + const selected = choice ?? linkRequestInitialMachine(item, machines); + const target = resolveTarget(item, machines, selected); + const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item); + // This client can mint a code there when it is connected to that + // environment with a session that may create pairing links. + const targetId = target.kind === "machine" ? target.environmentId : null; + const connected = usePreparedConnection(targetId); + const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope); + const canMint = + targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId); + const needsAddress = + target.kind === "address" || (target.kind === "machine" && target.urls.length === 0); + // An address the agent gave is already filled in; only one the user must type is asked for. + const asksAddress = needsAddress && !(item.url !== undefined && item.environmentId === undefined); + const useExisting = target.kind === "machine" && target.linked; + // A named machine with an address it answers at has nothing to choose before access. + const steps: ReadonlyArray = + pickMachine || asksAddress ? ["machine", "access"] : ["access"]; + const current: LinkStep = steps.includes(step) ? step : "access"; + const machineReady = + target.kind !== "none" && (useExisting || !needsAddress || address.trim().length > 0); + const ready = machineReady && (useExisting || canMint || pairingCode.trim().length > 0); + + const reset = () => { + setChoice(null); + setAddress(item.url ?? ""); + setAccess(linkRequestDefaultAccess(item)); + setPairingCode(""); + setStep("machine"); + setError(null); + }; + + const submit = async () => { + if (inFlight.current || target.kind === "none") return; + inFlight.current = true; + setBusy(true); + setError(null); + try { + let input; + if (target.kind === "machine" && target.linked) { + input = linkRequestAnswerInput(item, { + type: "use-existing", + environmentId: target.environmentId, + }); + } else { + let code = pairingCode; + if (canMint && targetId !== null) { + try { + code = await mintPairingCodeOn(targetId); + } catch (cause) { + setMintFailed((failed) => new Set(failed).add(targetId)); + setError(linkRequestFailureMessage(cause)); + return; + } + } + input = linkRequestAnswerInput(item, { + type: "link", + target: + target.kind === "address" + ? { url: address } + : { ...target, urls: needsAddress ? [address.trim()] : target.urls }, + access, + pairingCode: code, + }); + } + if (input === null) return; + const result = await answer({ environmentId: props.environmentId, input }); + if (result._tag === "Success") { + // The card switches to its answered row once the item updates. + setPairingCode(""); + props.onOpenChange(false); + return; + } + if (!isAtomCommandInterrupted(result)) { + setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); + } + } finally { + inFlight.current = false; + setBusy(false); + } + }; + + // The machine step ends the dialog when the machine is linked here already. + const finishesHere = current === "access" || useExisting; + + return ( + { + // An answer that lands after a close would still link, and would close a reopened dialog. + if (!next && busy) return; + props.onOpenChange(next); + if (!next) reset(); + }} + > + + + {steps.length > 1 && !useExisting ? ( + busy || (index === 1 && !machineReady)} + onStepChange={(index) => { + const next = steps[index]; + if (next !== undefined) setStep(next); + }} + /> + ) : null} + + +
    { + event.preventDefault(); + if (finishesHere) void submit(); + else if (machineReady) setStep("access"); + }} + > + {current === "machine" ? ( + <> + {pickMachine ? ( + { + setChoice(next); + setError(null); + }} + /> + ) : null} + {asksAddress ? ( + + ) : null} + {useExisting ? ( +

    + This environment is already linked to {targetName}. The agent can use that link + as it is; change its access in Settings → Connections. +

    + ) : null} + + ) : ( + <> + {item.url !== undefined && !pickMachine ? ( +

    {item.url}

    + ) : null} + {canMint ? null : ( + + )} + + + )} + {error !== null ? ( +

    + {error} +

    + ) : null} + +
    + + {current === "access" && steps.length > 1 ? ( + + ) : ( + + )} + + +
    +
    + ); +} + +/** The user's other machines, best match for the agent's hint first, then an address. */ +function MachinePicker(props: { + readonly machines: ReadonlyArray; + readonly value: string | null; + readonly disabled: boolean; + readonly onChange: (value: string) => void; +}) { + const labelId = useId(); + return ( +
    + + Machine + + props.onChange(next as string)} + > + {props.machines.map((machine) => ( + + ))} + + +
    + ); +} diff --git a/apps/web/src/components/chat/TimelineV2EventRow.tsx b/apps/web/src/components/chat/TimelineV2EventRow.tsx index a4d2adf902f3..25f81d7d2d43 100644 --- a/apps/web/src/components/chat/TimelineV2EventRow.tsx +++ b/apps/web/src/components/chat/TimelineV2EventRow.tsx @@ -18,6 +18,7 @@ import { SubagentElapsed, V2LifecycleRow, } from "./V2LifecycleRow"; +import { LinkRequestCard } from "./LinkRequestCard"; import { SecretRequestCard } from "./SecretRequestCard"; import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext"; import { v2EventPresentation, subagentGroupTiming } from "./TimelineV2EventRow.logic"; @@ -37,6 +38,15 @@ export function V2EventTimelineRow({ row }: { row: Extract ); } + if (item.type === "link_request") { + return ( + + ); + } if (isV2LifecycleItem(item)) { return ( void; + readonly disabled?: boolean; +}) { + const labelId = useId(); + const selected = accessConfig[value]; + return ( +
    + + What agents here may do there + + +

    + {selected.description} An agent never gets more access there than its own mode here. Below + full access, it can change only threads this link started, not that machine's own threads, + projects or settings. +

    +
    + ); +} diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index f3f877ba7f11..246e6754daa4 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -1,5 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; -import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import type { AuthMcpClientAccess, EnvironmentId, PeerLinkSummary } from "@t3tools/contracts"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -13,7 +13,7 @@ import { requestConfirmDialog } from "~/confirmDialog"; import { peerLinkEnvironment } from "~/state/peerLinks"; import { useEnvironmentQuery } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; -import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface"; +import { accessConfig } from "../auth/ConnectAgentSurface"; import { ConnectionStatusDot } from "../ConnectionStatusDot"; import { Button } from "../ui/button"; import { @@ -28,9 +28,9 @@ import { DialogTrigger, } from "../ui/dialog"; import { Input } from "../ui/input"; -import { RadioGroup } from "../ui/radio-group"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows"; +import { LinkAccessPicker } from "./LinkAccessPicker"; import { SettingsRow, SettingsSection, useRelativeTimeTick } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -161,7 +161,6 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi const [access, setAccess] = useState("approval-required"); const [busy, setBusy] = useState(false); const formId = useId(); - const accessLabelId = `${formId}-access`; const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" }); const handleOpenChange = (next: boolean) => { setOpen(next); @@ -242,26 +241,7 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi spellCheck={false} /> -
    - - What agents here may do there - - setAccess(value as AuthMcpClientAccess)} - > - {AuthMcpClientAccess.literals.map((option) => ( - - ))} - -

    - An agent never gets more access there than its own mode here. Below full access, it - can change only threads this link started, not that environment's own threads, - projects or settings. -

    -
    + diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 0d6956fa3789..a6cc00e1a8b8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -366,6 +366,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set readable.has(environment.environmentId)); } + +/** + * The user's other machines, for picking one to link `environmentId` to. + * Reads that environment's links only while `enabled`, since listing them + * asks every linked machine whether it answers. + */ +export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) { + const { environments } = useEnvironments(); + const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom); + const links = useEnvironmentQuery( + enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null, + ); + return linkableMachines({ + environments, + threadEnvironmentId: environmentId, + linkedIds: new Set(links.data?.links.map((link) => link.environmentId)), + connectAddresses: new Map( + [...discovery.environments].map(([id, found]) => [ + id, + found.environment.endpoint.httpBaseUrl, + ]), + ), + }); +} diff --git a/apps/web/src/state/peerPairingCode.ts b/apps/web/src/state/peerPairingCode.ts new file mode 100644 index 000000000000..dc3afa7b3ff5 --- /dev/null +++ b/apps/web/src/state/peerPairingCode.ts @@ -0,0 +1,42 @@ +import { mintPeerPairingCode } from "@t3tools/client-runtime/state/peerPairingCode"; +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { Atom, AtomRegistry } from "effect/reactivity"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { environmentSession } from "./session"; + +// Each read mints a new one-use code; nothing keeps one once it is read. +const peerPairingCodeAtom = Atom.family((environmentId: EnvironmentId) => + connectionAtomRuntime + .atom((get) => { + const prepared = Option.getOrNull( + get(environmentSession.preparedConnectionValueAtom(environmentId)), + ); + if (prepared === null) return Effect.never; + return mintPeerPairingCode(prepared); + }) + .pipe(Atom.withLabel(`peer-pairing-code:${environmentId}`)), +); + +/** + * A fresh pairing code minted on `environmentId` with this client's session + * there, for answering a link request. Fails with `PeerPairingCodeError` when + * the session may not create one. + */ +export function mintPairingCodeOn(environmentId: EnvironmentId): Promise { + const atom = peerPairingCodeAtom(environmentId); + appAtomRegistry.refresh(atom); + return Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + yield* AtomRegistry.mount(appAtomRegistry, atom); + return yield* AtomRegistry.getResult(appAtomRegistry, atom, { + suspendOnWaiting: true, + }).pipe(Effect.timeout("15 seconds")); + }), + ), + ); +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 00096ae4169f..76534bf6f459 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -256,6 +256,13 @@ choose **Link**, and enter the other machine's address and a pairing code from it. From a terminal, use `t3 environment link
    --pairing-code --access `. +You can also ask an agent to link a machine by name, such as "delegate this to +my vps". It shows a card in the thread where you pick the machine from the ones +this app knows (or enter an address) and the access, then approve. If this app +is connected to that machine with a session that manages access there, it uses +that session; otherwise paste a pairing code from that machine's +**Settings → Connections**. + - The access you pick is the most agents from this machine may do there. An agent also never gets more there than its own mode here. - Threads a link starts are marked **From** and this machine's name there. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 2bfcb017090b..b229f5f2e69a 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -55,6 +55,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./link-request": { + "types": "./src/linkRequest.ts", + "default": "./src/linkRequest.ts" + }, "./scheduled-task-webhook": { "types": "./src/scheduledTaskWebhook.ts", "default": "./src/scheduledTaskWebhook.ts" @@ -203,6 +207,10 @@ "types": "./src/state/peerLinks.ts", "default": "./src/state/peerLinks.ts" }, + "./state/peerPairingCode": { + "types": "./src/state/peerPairingCode.ts", + "default": "./src/state/peerPairingCode.ts" + }, "./state/preview": { "types": "./src/state/preview.ts", "default": "./src/state/preview.ts" diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts new file mode 100644 index 000000000000..29ec717f9456 --- /dev/null +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -0,0 +1,255 @@ +import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { describe, expect, it } from "vite-plus/test"; + +import { BearerConnectionProfile } from "./connection/catalog.ts"; +import { BearerConnectionTarget, RelayConnectionTarget } from "./connection/model.ts"; +import type { EnvironmentPresentation } from "./connection/presentation.ts"; +import { + linkableMachines, + linkRequestAnswerInput, + linkRequestDisplay, + linkRequestFailureMessage, + linkRequestInitialMachine, + rankMachinesByHint, +} from "./linkRequest.ts"; + +const item = { + id: TurnItemId.make("turn-item:link-request:1"), + threadId: ThreadId.make("thread-1"), +}; +const asked = { url: "https://box.example.ts.net", label: "Box" }; +const accessLabel = (access: string) => `<${access}>`; + +describe("linkRequestDisplay", () => { + it("names the environment linked and the access the user chose", () => { + expect( + linkRequestDisplay( + { ...asked, linkStatus: "linked", linkedLabel: "Box", linkedAccess: "auto" }, + "local", + accessLabel, + ), + ).toEqual({ kind: "answered", outcome: "linked", label: "Linked Box · " }); + }); + + it("shows why a link failed, and never offers the actions outside the asking thread", () => { + expect( + linkRequestDisplay( + { ...asked, linkStatus: "failed", failure: "Pairing code expired." }, + "local", + accessLabel, + ), + ).toMatchObject({ outcome: "failed", label: "Could not link: Pairing code expired." }); + expect( + linkRequestDisplay({ ...asked, linkStatus: "pending" }, "inherited", accessLabel), + ).toMatchObject({ kind: "pending-elsewhere" }); + }); +}); + +describe("linkRequestAnswerInput", () => { + const vps = { + environmentId: EnvironmentId.make("environment-vps"), + label: "VPS", + urls: ["https://vps.ts.net", "http://10.0.0.2:3773"], + }; + + it("answers with the machine picked and every address known for it", () => { + expect( + linkRequestAnswerInput(item, { + type: "link", + target: vps, + access: "auto", + pairingCode: " abc ", + }), + ).toEqual({ + threadId: item.threadId, + turnItemId: item.id, + answer: { type: "link", ...vps, access: "auto", pairingCode: "abc" }, + }); + expect( + linkRequestAnswerInput(item, { + type: "link", + target: { url: " https://box.ts.net " }, + access: "auto", + pairingCode: "abc", + }), + ).toMatchObject({ answer: { urls: ["https://box.ts.net"] } }); + }); + + it("refuses a blank code, a blank address, or a machine with no address", () => { + const blank = (target: Parameters[1] & { type: "link" }) => + linkRequestAnswerInput(item, target); + expect(blank({ type: "link", target: vps, access: "auto", pairingCode: " " })).toBeNull(); + expect( + blank({ type: "link", target: { url: " " }, access: "auto", pairingCode: "abc" }), + ).toBeNull(); + expect( + blank({ type: "link", target: { ...vps, urls: [] }, access: "auto", pairingCode: "abc" }), + ).toBeNull(); + }); +}); + +const presentation = ( + id: string, + label: string, + options: { + readonly saved?: ReadonlyArray; + readonly reported?: ReadonlyArray; + readonly connected?: boolean; + } = {}, +): EnvironmentPresentation & { readonly environmentId: EnvironmentId } => { + const environmentId = EnvironmentId.make(id); + const [first, ...rest] = (options.saved ?? []).map((httpBaseUrl, index) => { + const connectionId = `${id}-${index}`; + return { + target: new BearerConnectionTarget({ environmentId, label, connectionId }), + profile: Option.some( + new BearerConnectionProfile({ + connectionId, + environmentId, + label, + httpBaseUrl, + wsBaseUrl: httpBaseUrl, + }), + ), + }; + }); + return { + environmentId, + entry: { + ...(first ?? { + target: new RelayConnectionTarget({ environmentId, label }), + profile: Option.none(), + }), + ...(rest.length === 0 ? {} : { alternateRoutes: rest }), + enabled: true, + }, + connection: { + phase: options.connected === false ? "offline" : "connected", + error: null, + traceId: null, + }, + serverConfig: + options.reported === undefined + ? null + : ({ + environment: { platform: { machine: "laptop" } }, + directEndpoints: options.reported.map((httpBaseUrl) => ({ + kind: "tailnet", + httpBaseUrl, + })), + } as unknown as ServerConfig), + }; +}; + +describe("linkableMachines", () => { + it("lists the other machines with reported addresses before saved ones, once each", () => { + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] }); + const vps = presentation("environment-vps", "VPS", { + saved: ["https://vps.example.com", "https://vps.ts.net"], + reported: ["https://vps.ts.net"], + }); + const mini = presentation("environment-mini", "Mini", { connected: false }); + expect( + linkableMachines({ + environments: [here, vps, mini], + threadEnvironmentId: here.environmentId, + linkedIds: new Set([mini.environmentId]), + connectAddresses: new Map(), + }), + ).toEqual([ + { + environmentId: vps.environmentId, + label: "VPS", + machine: "laptop", + connected: true, + linked: false, + urls: ["https://vps.ts.net", "https://vps.example.com"], + }, + { + environmentId: mini.environmentId, + label: "Mini", + machine: "server", + connected: false, + linked: true, + urls: [], + }, + ]); + }); + + it("reaches a machine saved only over T3 Connect at its Connect address", () => { + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] }); + const box = presentation("environment-box", "Box"); + const [listed] = linkableMachines({ + environments: [here, box], + threadEnvironmentId: here.environmentId, + linkedIds: new Set(), + connectAddresses: new Map([[box.environmentId, "https://box.t3.example"]]), + }); + expect(listed?.urls).toEqual(["https://box.t3.example"]); + // Until discovery has found it, there is no address to offer. + expect( + linkableMachines({ + environments: [here, box], + threadEnvironmentId: here.environmentId, + linkedIds: new Set(), + connectAddresses: new Map(), + })[0]?.urls, + ).toEqual([]); + }); +}); + +describe("rankMachinesByHint", () => { + const machines = [ + { label: "Old vps box" }, + { label: "VPS-2" }, + { label: "Mac mini" }, + { label: "vps" }, + ]; + + it("puts an exact name first, then a prefix, then a substring, keeping order within each", () => { + expect(rankMachinesByHint(machines, " VPS ").map((machine) => machine.label)).toEqual([ + "vps", + "VPS-2", + "Old vps box", + "Mac mini", + ]); + expect(rankMachinesByHint(machines, undefined)).toBe(machines); + }); + + it("preselects the card's machine, or the hint's match, and nothing for a hint that matches none", () => { + const listed = [ + { environmentId: EnvironmentId.make("environment-mini"), label: "Mac mini" }, + { environmentId: EnvironmentId.make("environment-vps"), label: "Hetzner VPS" }, + ].map( + (machine) => + ({ ...machine, machine: "server", connected: true, linked: false, urls: [] }) as const, + ); + expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps"); + // Agents pass the user's words, which name the machine among others. + expect(linkRequestInitialMachine({ hint: "my mac mini" }, listed)).toBe("environment-mini"); + expect(linkRequestInitialMachine({ hint: "my mac" }, listed)).toBe("environment-mini"); + expect(linkRequestInitialMachine({ hint: "the hetzner vps box" }, listed)).toBe( + "environment-vps", + ); + expect(linkRequestInitialMachine({ hint: "desk" }, listed)).toBeNull(); + expect(linkRequestInitialMachine({ hint: "minimal" }, listed)).toBeNull(); + expect( + linkRequestInitialMachine( + { environmentId: EnvironmentId.make("environment-x"), hint: "vps" }, + listed, + ), + ).toBe("environment-x"); + }); +}); + +describe("linkRequestFailureMessage", () => { + it("passes through only known user-facing errors", () => { + expect( + linkRequestFailureMessage({ _tag: "PeerLinkRequestError", message: "Already answered." }), + ).toBe("Already answered."); + expect(linkRequestFailureMessage({ _tag: "SchemaError", message: "code=abc" })).toBe( + "Could not answer the request. Try again.", + ); + }); +}); diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts new file mode 100644 index 000000000000..58d6cd5a69c0 --- /dev/null +++ b/packages/client-runtime/src/linkRequest.ts @@ -0,0 +1,249 @@ +import { + type AuthMcpClientAccess, + type EnvironmentId, + type EnvironmentMachineKind, + type OrchestrationV2TurnItem, + type PeerLinkRequestAnswerInput, + resolveEnvironmentMachineKind, +} from "@t3tools/contracts"; + +import type { EnvironmentPresentation } from "./connection/presentation.ts"; +import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts"; + +export type LinkRequestItem = Extract; + +/** The access a request opens with: the agent's suggestion, else supervised. */ +export const linkRequestDefaultAccess = ( + item: Pick, +): AuthMcpClientAccess => item.requestedAccess ?? "approval-required"; + +/** What the card calls the other environment: its own name, else the address asked for. */ +export const linkRequestTargetName = (item: Pick): string => + item.label?.trim() || item.url || "a machine"; + +/** A machine the user could link a thread's environment to. */ +export interface LinkableMachine { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly machine: EnvironmentMachineKind; + readonly connected: boolean; + /** Whether the thread's environment already has a link to it. */ + readonly linked: boolean; + /** + * Where the client knows it answers, most preferred first: the addresses it + * reports, then its saved routes, a T3 Connect route by its Connect address. + * The server keeps only those that answer as this machine. Empty for a + * machine reached only over SSH, whose forward lives in this client. + */ + readonly urls: ReadonlyArray; +} + +/** + * The machines in the client's catalog other than the thread's own + * environment, in catalog order. `linkedIds` are the environments the thread's + * environment links to already. `connectAddresses` are the T3 Connect + * addresses relay discovery found, by environment id: a server reaches a + * machine there as a browser does, so a Connect route is a usable address. + */ +export function linkableMachines(input: { + readonly environments: ReadonlyArray< + EnvironmentPresentation & { readonly environmentId: EnvironmentId } + >; + readonly threadEnvironmentId: EnvironmentId; + readonly linkedIds: ReadonlySet; + readonly connectAddresses: ReadonlyMap; +}): ReadonlyArray { + return input.environments + .filter((environment) => environment.environmentId !== input.threadEnvironmentId) + .map((environment) => { + const reported = (environment.serverConfig?.directEndpoints ?? []).map( + (endpoint) => endpoint.httpBaseUrl, + ); + const connect = input.connectAddresses.get(environment.environmentId); + const saved = connectionRoutes(environment.entry).flatMap((route) => { + const url = + route.target._tag === "RelayConnectionTarget" ? connect : routeHttpBaseUrl(route); + return url === null || url === undefined ? [] : [url]; + }); + return { + environmentId: environment.environmentId, + label: environment.entry.target.label, + machine: resolveEnvironmentMachineKind(environment.serverConfig), + connected: environment.connection.phase === "connected", + linked: input.linkedIds.has(environment.environmentId), + urls: [...new Set([...reported, ...saved])], + }; + }); +} + +const words = (text: string) => + ` ${text + .toLowerCase() + .split(/[^\p{L}\p{N}]+/u) + .join(" ") + .trim()} `; +const NO_MATCH = 4; + +/** + * How well a machine's name matches the agent's hint, which is often the + * user's own words ("my box"): exact, prefix, substring, then a hint that + * names it among other words ("the box on hetzner"). + */ +const hintRank = (label: string, hint: string) => { + const name = label.trim().toLowerCase(); + const wanted = hint + .trim() + .toLowerCase() + .replace(/^(?:my|our|the)\s+/, ""); + if (name === wanted) return 0; + if (name.startsWith(wanted)) return 1; + if (name.includes(wanted)) return 2; + if (words(wanted).includes(words(name))) return 3; + return NO_MATCH; +}; + +/** The machines best match for the agent's hint first, each rank in catalog order. */ +export function rankMachinesByHint( + machines: ReadonlyArray, + hint: string | undefined, +): ReadonlyArray { + if (hint === undefined || hint.trim().length === 0) return machines; + return machines + .map((machine, index) => ({ machine, index, rank: hintRank(machine.label, hint) })) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .map(({ machine }) => machine); +} + +/** The machine a card opens on: the one it names, else the hint's best match. */ +export function linkRequestInitialMachine( + item: Pick, + machines: ReadonlyArray, +): EnvironmentId | null { + if (item.environmentId !== undefined) return item.environmentId; + if (item.hint === undefined) return null; + const [best] = rankMachinesByHint(machines, item.hint); + return best !== undefined && hintRank(best.label, item.hint) < NO_MATCH + ? best.environmentId + : null; +} + +/** What a link request card shows: the actions while pending, otherwise a one-line outcome. */ +export type LinkRequestDisplay = + | { readonly kind: "pending" } + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { + readonly kind: "answered"; + readonly outcome: "linked" | "declined" | "ended" | "failed"; + readonly label: string; + }; + +/** + * `visibility` is the projected row's: a request inherited from another + * thread (a fork) can only be answered where it was asked. `accessLabel` + * names an access level the way the client's access picker does. + */ +export function linkRequestDisplay( + item: Pick< + LinkRequestItem, + "linkStatus" | "label" | "url" | "linkedLabel" | "linkedAccess" | "failure" + >, + visibility: "local" | "inherited" | "synthetic", + accessLabel: (access: AuthMcpClientAccess) => string, +): LinkRequestDisplay { + switch (item.linkStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: "Waiting for an answer in the original thread" }; + case "linked": + return { + kind: "answered", + outcome: "linked", + label: `Linked ${item.linkedLabel ?? linkRequestTargetName(item)}${ + item.linkedAccess === undefined ? "" : ` · ${accessLabel(item.linkedAccess)}` + }`, + }; + case "declined": + return { kind: "answered", outcome: "declined", label: "Declined" }; + case "failed": + return { + kind: "answered", + outcome: "failed", + label: `Could not link: ${item.failure ?? "the other environment refused"}`, + }; + case "cancelled": + return { kind: "answered", outcome: "ended", label: "Request ended" }; + } +} + +/** + * Builds the RPC payload for an answer. A link with a blank code returns null, + * since the server rejects it; callers keep Link disabled instead. + */ +export function linkRequestAnswerInput( + item: Pick, + answer: + | { + readonly type: "link"; + /** The machine picked, or an address typed in its place. */ + readonly target: + | Pick + | { readonly url: string }; + readonly access: AuthMcpClientAccess; + readonly pairingCode: string; + } + | { readonly type: "use-existing"; readonly environmentId: EnvironmentId } + | { readonly type: "decline" }, +): PeerLinkRequestAnswerInput | null { + const base = { threadId: item.threadId, turnItemId: item.id }; + if (answer.type !== "link") return { ...base, answer }; + const pairingCode = answer.pairingCode.trim(); + if (pairingCode.length === 0) return null; + const { target } = answer; + if ("url" in target) { + const url = target.url.trim(); + if (url.length === 0) return null; + return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } }; + } + const [first, ...rest] = target.urls; + if (first === undefined) return null; + return { + ...base, + answer: { + type: "link", + environmentId: target.environmentId, + label: target.label, + urls: [first, ...rest], + access: answer.access, + pairingCode, + }, + }; +} + +/** Failures whose message is written for the user and never echoes the request payload. */ +const USER_FACING_FAILURE_TAGS = new Set([ + "PeerLinkRequestError", + "EnvironmentAuthorizationError", + "PeerPairingCodeError", +]); + +/** + * Inline error copy for a failed answer. Only known errors pass their message + * through: anything else (transport or encoding failures) gets the generic + * copy, so the pairing code can never surface in the UI. + */ +export function linkRequestFailureMessage(failure: unknown): string { + if ( + typeof failure === "object" && + failure !== null && + "_tag" in failure && + typeof failure._tag === "string" && + USER_FACING_FAILURE_TAGS.has(failure._tag) && + "message" in failure && + typeof failure.message === "string" && + failure.message.trim().length > 0 + ) { + return failure.message; + } + return "Could not answer the request. Try again."; +} diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 86fa95636538..ed28cd13e3a0 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -423,6 +423,30 @@ it.effect( ), ); +it.effect("requires access management to answer a link request", () => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + registry.set(sessions(env), AsyncResult.success(grant(true))); + const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest); + expect(registry.get(answer.permissionAtom(env))).toBe(false); + expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe( + AuthAccessWriteScope, + ); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthAccessWriteScope], + permissions: [AuthAccessWriteScope], + }), + ); + expect(registry.get(answer.permissionAtom(env))).toBe(true); + yield* answer.authorize(registry, env); + }), + ), +); + it.effect("honors exact empty permissions and preserves legacy parent grants", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts new file mode 100644 index 000000000000..0799c1cd7115 --- /dev/null +++ b/packages/client-runtime/src/state/peerPairingCode.ts @@ -0,0 +1,75 @@ +/** + * A pairing code for linking, minted on the environment being linked to with + * the user's own session there, so a link card can be answered without the + * user fetching a code by hand. The code is one-use, carries only what an + * agent sign-in needs, and goes straight into the link answer. + */ +import { + type AuthGrantScope, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, +} from "@t3tools/contracts"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import type * as HttpClient from "effect/http/HttpClient"; + +import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; +import type { PreparedConnection } from "../connection/model.ts"; +import * as ManagedRelay from "../relay/managedRelay.ts"; +import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts"; + +const MINT_TIMEOUT_MS = 8_000; +const PEER_PAIRING_CODE_LABEL = "T3 Code link"; +/** An agent signing in there needs these, whatever access the user picks. */ +const LINK_SCOPES: ReadonlyArray = [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, +]; + +/** Minting failed; the user can still paste a code from the other environment. */ +export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{ + readonly reason: "not_allowed" | "unavailable"; + readonly cause: unknown; +}> { + override get message(): string { + return this.reason === "not_allowed" + ? "Your session there cannot create pairing codes. Paste a code from there instead." + : "Could not get a pairing code from there. Paste a code from there instead."; + } +} + +export const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* ( + prepared: PreparedConnection, +): Effect.fn.Return { + const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner); + const remoteAuthorization = yield* Effect.serviceOption( + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, + ); + const minted = yield* executeAuthenticatedEnvironmentHttpRequest({ + prepared, + signer, + remoteAuthorization, + group: "auth", + method: "POST", + url: (urls) => urls.pairingCredential(), + timeoutMs: MINT_TIMEOUT_MS, + request: ({ client, headers }) => + client.pairingCredential({ + headers, + payload: { label: PEER_PAIRING_CODE_LABEL, scopes: LINK_SCOPES }, + }), + }).pipe( + Effect.mapError( + (cause) => + new PeerPairingCodeError({ + reason: + cause._tag === "EnvironmentScopeRequiredError" || + cause._tag === "EnvironmentOperationForbiddenError" + ? "not_allowed" + : "unavailable", + cause, + }), + ), + ); + return minted.credential; +}); diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 4361592601f0..ac2ed7d8b1a4 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1347,6 +1347,16 @@ export function createServerEnvironmentAtoms( JSON.stringify([environmentId, input.threadId, input.turnItemId]), }, }), + // Like a secret card's answer: off the config lane, one per card at a time. + answerLinkRequest: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:peer-links:answer-request", + tag: WS_METHODS.peerLinksAnswerRequest, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + JSON.stringify([environmentId, input.threadId, input.turnItemId]), + }, + }), refreshUsageRates: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:refresh-usage-rates", tag: WS_METHODS.serverRefreshUsageRates, diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 966a823b5f27..15f1ae660bd1 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -336,6 +336,16 @@ export function summarizeT3ToolCalls( case "environment-links": label = phrase("Listed", "list", `linked environments ${times}`); break; + case "environment-link": + label = phrase("Asked to link", "ask to link", quantity(selected.length, "environment")); + break; + case "environment-unlink": + label = phrase( + "Forgot", + "forget", + quantity(countEntities(entityIds("environmentId")), "linked environment"), + ); + break; case "attachment-prepare": label = phrase( "Prepared", diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 1981d490776f..0429cfb26e59 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -53,6 +53,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.peerLinksLink]: AuthAccessWriteScope, [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope, + // A link lets every agent here reach the other environment: Settings' bar. + [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 3d4b0dbdad2e..de7128c4cc7e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1402,6 +1402,42 @@ const OrchestrationV2SecretRequestFields = { secretStatus: OrchestrationV2SecretRequestStatus, } as const; +export const OrchestrationV2LinkRequestStatus = Schema.Literals([ + "pending", + "linked", + "declined", + "cancelled", + "failed", +]); +export type OrchestrationV2LinkRequestStatus = typeof OrchestrationV2LinkRequestStatus.Type; + +/** + * An agent asked the user to link another environment. The user picks the + * access; the pairing code never passes through orchestration, so the item + * carries only what was asked and how it ended. + */ +const OrchestrationV2LinkRequestFields = { + type: Schema.Literal("link_request"), + /** The address the agent named, if it named one. */ + url: Schema.optional(TrimmedNonEmptyString), + reason: Schema.String, + /** + * The environment the agent named, or the one answering at `url`. Without + * either the user picks the machine in the card. + */ + environmentId: Schema.optional(EnvironmentId), + label: Schema.optional(Schema.String), + /** A phrase from the user's words, such as "vps", that preselects a machine. */ + hint: Schema.optional(Schema.String), + /** The access the agent suggested; the user's choice is final. */ + requestedAccess: Schema.optional(AuthMcpClientAccess), + linkStatus: OrchestrationV2LinkRequestStatus, + linkedEnvironmentId: Schema.optional(EnvironmentId), + linkedLabel: Schema.optional(Schema.String), + linkedAccess: Schema.optional(AuthMcpClientAccess), + failure: Schema.optional(Schema.String), +} as const; + export const OrchestrationV2TurnItem = Schema.Union([ Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -1583,6 +1619,10 @@ export const OrchestrationV2TurnItem = Schema.Union([ ...OrchestrationV2TurnItemBaseFields, ...OrchestrationV2SecretRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemBaseFields, + ...OrchestrationV2LinkRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("subagent"), @@ -2348,6 +2388,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ ...OrchestrationV2TurnItemJsonBaseFields, ...OrchestrationV2SecretRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemJsonBaseFields, + ...OrchestrationV2LinkRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("subagent"), @@ -3206,6 +3250,37 @@ const OrchestrationV2InternalCommand = Schema.Union([ placeholder: Schema.optional(Schema.String), secretStatus: OrchestrationV2SecretRequestStatus, }), + /** + * Records or updates a link an agent asked the user to make. Internal so no + * client can mark a request linked without the link being made. + */ + Schema.Struct({ + type: Schema.Literal("link_request.record"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + nodeId: NodeId, + turnItemId: TurnItemId, + url: Schema.optional(TrimmedNonEmptyString), + reason: Schema.String, + environmentId: Schema.optional(EnvironmentId), + label: Schema.optional(Schema.String), + hint: Schema.optional(Schema.String), + requestedAccess: Schema.optional(AuthMcpClientAccess), + linkStatus: OrchestrationV2LinkRequestStatus, + linkedEnvironmentId: Schema.optional(EnvironmentId), + linkedLabel: Schema.optional(Schema.String), + linkedAccess: Schema.optional(AuthMcpClientAccess), + failure: Schema.optional(Schema.String), + /** Tells the agent how the card ended, in the same commit that closes it. */ + wake: Schema.optional( + Schema.Struct({ + messageId: MessageId, + text: Schema.String, + notification: OrchestrationV2Notification, + }), + ), + }), ]); export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalCommand.Type; diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 838fd6674aa2..f6a2cdef900d 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -627,6 +627,8 @@ export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLi export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({ environmentId: EnvironmentId, links: Schema.Array(OrchestratorMcpEnvironmentLink), + /** What to do when the machine the user means is not among `links`. */ + notListed: Schema.String, }); export type OrchestratorMcpEnvironmentLinksResult = typeof OrchestratorMcpEnvironmentLinksResult.Type; @@ -764,6 +766,79 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([ ]); export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type; +export const OrchestratorMcpEnvironmentLinkInput = Schema.Struct({ + environmentId: Schema.optional(EnvironmentId).annotate({ + description: + "The environment to link, when you know it, e.g. from a machine the user mentioned. Omit it otherwise: the user picks the machine in the card.", + }), + url: Schema.optional(TrimmedNonEmptyString).annotate({ + description: + "Only when the user gave an address: its https, Tailscale, LAN or loopback base URL. Never guess one.", + }), + hint: Schema.optional(TrimmedNonEmptyString).annotate({ + description: + 'A short phrase from the user\'s words naming the machine, e.g. "vps" or "mac mini". It only preselects a machine in the card.', + }), + reason: Schema.optional(TrimmedNonEmptyString).annotate({ + description: "One sentence on why, shown on the card.", + }), + requestedAccess: Schema.optional(AuthMcpClientAccess).annotate({ + description: + "The access to suggest. The user picks the access in the card; it defaults to approval-required.", + }), + clientRequestId: Schema.optional(OrchestratorMcpClientRequestId).annotate({ + description: + "Reuse when retrying a call that lost its result, so the user sees one card and its current outcome is returned. Use a new id to ask again.", + }), +}); +export type OrchestratorMcpEnvironmentLinkInput = typeof OrchestratorMcpEnvironmentLinkInput.Type; + +export const OrchestratorMcpEnvironmentLinkResult = Schema.Union([ + Schema.Struct({ + status: Schema.Literal("pending").annotate({ + description: + "The card is waiting for the user. Their answer arrives as a message in this thread.", + }), + turnItemId: TurnItemId, + }), + Schema.Struct({ + status: Schema.Literal("linked"), + environmentId: EnvironmentId.annotate({ + description: "Pass it as environmentId to act there; t3_environment_links lists it.", + }), + label: Schema.String, + access: AuthMcpClientAccess.annotate({ description: "The access the user chose." }), + }), + Schema.Struct({ + status: Schema.Literals(["declined", "cancelled"]).annotate({ + description: + "declined: the user chose not to. cancelled: the card closed unanswered, when the thread was stopped or archived.", + }), + }), + Schema.Struct({ + status: Schema.Literal("failed"), + message: Schema.String.annotate({ + description: "Why the other environment refused the link, as the user saw it.", + }), + }), +]); +export type OrchestratorMcpEnvironmentLinkResult = typeof OrchestratorMcpEnvironmentLinkResult.Type; + +export const OrchestratorMcpEnvironmentUnlinkInput = Schema.Struct({ + environmentId: EnvironmentId.annotate({ + description: "The linked environment to forget, from t3_environment_links.", + }), +}); +export type OrchestratorMcpEnvironmentUnlinkInput = + typeof OrchestratorMcpEnvironmentUnlinkInput.Type; + +export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({ + environmentId: EnvironmentId, + removed: Schema.Boolean, +}); +export type OrchestratorMcpEnvironmentUnlinkResult = + typeof OrchestratorMcpEnvironmentUnlinkResult.Type; + export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, scheduledTaskId: ScheduledTaskId, diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 022b1b9b9f8c..7882e8d2c74c 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -1,7 +1,7 @@ import * as Schema from "effect/Schema"; import { AuthMcpClientAccess } from "./auth.ts"; -import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts"; /** * A link from this environment to another one (the peer). This environment @@ -40,6 +40,13 @@ export const PeerLinkCreateInput = Schema.Struct({ /** A pairing code from the peer (`t3 pair` there, or its Connections settings). */ pairingCode: TrimmedNonEmptyString, access: AuthMcpClientAccess, + /** + * The environment the user means. Addresses that answer as another one are + * skipped, and only those that answer as this one are kept. + */ + expectedEnvironmentId: Schema.optionalKey(EnvironmentId), + /** What the user calls that environment, to name it when it cannot be reached. */ + expectedLabel: Schema.optionalKey(TrimmedNonEmptyString), }); export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type; @@ -64,3 +71,60 @@ export class PeerLinkError extends Schema.TaggedError()("PeerLink message: Schema.String, cause: Schema.optionalKey(Schema.Defect()), }) {} + +/** + * The user's answer to an agent asking to link an environment. The pairing + * code is used once to link and is never recorded; the thread learns only the + * outcome and the access the user chose. + */ +export const PeerLinkRequestAnswerInput = Schema.Struct({ + threadId: ThreadId, + turnItemId: TurnItemId, + answer: Schema.Union([ + Schema.Struct({ + type: Schema.Literal("link"), + /** The machine the user picked, when they picked one rather than typing an address. */ + environmentId: Schema.optionalKey(EnvironmentId), + /** What the client calls that machine. */ + label: Schema.optionalKey(TrimmedNonEmptyString), + /** The addresses the client knows for that machine, most preferred first. */ + urls: Schema.NonEmptyArray(TrimmedNonEmptyString), + access: AuthMcpClientAccess, + pairingCode: TrimmedNonEmptyString, + }), + /** Answers with a machine this environment is already linked to, as it is. */ + Schema.Struct({ type: Schema.Literal("use-existing"), environmentId: EnvironmentId }), + Schema.Struct({ type: Schema.Literal("decline") }), + ]), +}); +export type PeerLinkRequestAnswerInput = typeof PeerLinkRequestAnswerInput.Type; + +const PEER_LINK_REQUEST_FAILURE_MESSAGES = { + load_failed: "Could not load the link request.", + not_found: "This link request no longer exists.", + already_answered: "This link request was already answered.", + record_failed: "Could not update the link request.", +} as const; + +export const PeerLinkRequestFailureReason = Schema.Literals( + Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array< + keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES + >, +); +export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type; + +/** + * Answering a link request failed before anything was linked. A link the + * other environment refused is not this error: the card records it as failed. + */ +export class PeerLinkRequestError extends Schema.TaggedError()( + "PeerLinkRequestError", + { + reason: PeerLinkRequestFailureReason, + cause: Schema.optionalKey(Schema.Defect()), + }, +) { + override get message(): string { + return PEER_LINK_REQUEST_FAILURE_MESSAGES[this.reason]; + } +} diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 2973a5486237..12e0fa22f714 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -20,6 +20,8 @@ import { PeerLinkError, PeerLinkRemoveInput, PeerLinkRemoveResult, + PeerLinkRequestAnswerInput, + PeerLinkRequestError, PeerLinkSummary, } from "./peerLink.ts"; import { @@ -493,6 +495,7 @@ export const WS_METHODS = { peerLinksList: "peerLinks.list", peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", + peerLinksAnswerRequest: "peerLinks.answerRequest", serverGetSettings: "server.getSettings", serverUpdateSettings: "server.updateSettings", serverDiscoverSourceControl: "server.discoverSourceControl", @@ -784,6 +787,11 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, { + payload: PeerLinkRequestAnswerInput, + error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), +}); + const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, { payload: Schema.Struct({}), success: ServerSettings, @@ -1941,6 +1949,7 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksListRpc, WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, + WsPeerLinksAnswerRequestRpc, WsServerDiscoverSourceControlRpc, WsServerSearchAcpRegistryRpc, WsServerPrepareAcpRegistryAgentRpc, diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 11fe520364a7..0188a2e7d83e 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -15,6 +15,7 @@ The \`t3-code\` MCP server provides app-owned orchestration. Treat these concept - For every T3 delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. Do not use \`t3_thread_send\` on \`childThreadId\` to continue a delegated review.`, `- \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing. - \`t3_environment_links\` lists the user's other T3 Code environments that this one is linked to, such as another machine. To work there, pass that \`environmentId\` to any T3 tool that takes one, such as \`t3_thread_launch\`, \`t3_thread_send\`, \`t3_pending_request_respond\`, \`t3_queue_list\`, or \`t3_project_list\`; project, thread, run, and model ids then belong to that environment, so pass \`threadId\` explicitly. Work there runs within your own modes and the link's access. +- When the user names a machine that is not linked yet ("delegate this to my vps"), call \`t3_environment_link\` without an address and pass a \`hint\` from their words; pass \`environmentId\` instead when a machine the user mentioned names it. The user picks the machine and its access in a card and the outcome arrives as a message in this thread, so do not wait or poll; never ask for a pairing code in chat. - When you need a secret from the user (a token, API key, or webhook signing secret), call \`request_secret\` so they enter it privately, then pass the returned \`secretRef\` to the tool that needs it, e.g. \`signature.secretRef\` on a webhook task for a sender that signs requests such as GitHub. A \`secretRef\` works once. Never ask for a secret in chat, never invent one, and never repeat one. - To mention another thread to the user, link it as \`[title](t3-thread://v1/)\` with its exact \`threadId\`, not URL-encoded. T3 Code opens the thread in the app and shows its current title. Name a thread in a linked environment by title instead: its link would open here.`, `### Choose the workspace before starting a new thread diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 975361f36b1c..542c688ad469 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -51,6 +51,8 @@ export type T3McpToolSummaryAction = | "project-clone" | "environment-read" | "environment-links" + | "environment-link" + | "environment-unlink" | "environment-update" | "attachment-prepare" | "attachment-discard" @@ -314,6 +316,14 @@ const T3_MCP_TOOLS: Readonly> = { ["List", "Listing", "Listed", "linked environments"], "environment-links", ), + t3_environment_link: tool( + ["Ask to link", "Asking to link", "Asked to link", "an environment"], + "environment-link", + ), + t3_environment_unlink: tool( + ["Forget", "Forgetting", "Forgot", "a linked environment"], + "environment-unlink", + ), t3_environment_preferences_update: tool( ["Update", "Updating", "Updated", "environment preferences"], "environment-update", From faa16e36e19f2337243bc713efed1f2205afdffe Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:57:23 -0700 Subject: [PATCH 129/408] fix(server): a link card's id names the provider session that asked A later provider session in the same thread reusing a clientRequestId got the earlier session's card back, even for another machine. The card id now includes the caller's request namespace, as the command id already did. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/PeerLinkRequests.test.ts | 23 +++++++++++++++++++ apps/server/src/peer/PeerLinkRequests.ts | 7 +++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index 661a4bdef83d..084e5220580f 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -479,6 +479,29 @@ it.live("a retry of a pending request returns pending and shows no second card", ), ); +it.live("a later provider session reusing a clientRequestId gets a card of its own", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + const first = yield* a.call({ url: b.url, clientRequestId: "link" }); + const later = yield* a.call( + { environmentId: box.environmentId, clientRequestId: "link" }, + { + ...scope, + requestNamespace: "provider-session:laptop-2", + thread: { ...scope.thread!, providerSessionId: "provider-session:laptop-2" }, + }, + ); + expect(later.structuredContent).toMatchObject({ status: "pending" }); + expect(later.structuredContent).not.toEqual(first.structuredContent); + const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter( + (item) => item.type === "link_request", + ); + expect(cards).toHaveLength(2); + }), + ), +); + it.live("a declined request links nothing and tells the agent", () => withBoth((a, b) => Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts index c66d5782a70c..b4a52745415f 100644 --- a/apps/server/src/peer/PeerLinkRequests.ts +++ b/apps/server/src/peer/PeerLinkRequests.ts @@ -174,10 +174,11 @@ const make = Effect.gen(function* () { } } const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); - // Turn item ids are global; scope the key to this thread. A retry with - // the same clientRequestId finds this card and records nothing. + // Turn item ids are global; scope the key to this thread and provider + // session, since a later session may reuse it. A retry with the same + // clientRequestId finds this card and records nothing. const turnItemId = TurnItemId.make( - `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(key)}`, + `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(scope.requestNamespace)}:${encodeURIComponent(key)}`, ); if (input.clientRequestId !== undefined) { const existing = yield* readCard(threadId, turnItemId).pipe(Effect.mapError(unreadable)); From 92a1697a2e0d455aa06f51960866ae0a9ed05723 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:01:12 -0700 Subject: [PATCH 130/408] fix(server): an expired link goes through the link card t3_environment_link told the agent a machine was linked whenever a row existed, and "Use this link" accepted it, even after the link expired. The agent then failed on its first call and the user had no way to renew it from the card. Both now treat an expired link as no link, so the card asks for a new pairing code. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/PeerLinkRequests.test.ts | 46 +++++++++++++++++++ apps/server/src/peer/PeerLinkRequests.ts | 32 +++++++++---- 2 files changed, 68 insertions(+), 10 deletions(-) diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index 084e5220580f..6b671b2cdc26 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -16,8 +16,10 @@ import { ThreadId, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -53,6 +55,7 @@ import * as PeerLinks from "./PeerLinks.ts"; import { descriptorOf, layerLinkingEnvironment, + linkTo, servePeer, type ServedPeer, } from "./PeerLinks.testkit.ts"; @@ -367,6 +370,26 @@ const errorOf = (result: McpSchema.CallToolResult) => { return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined; }; +/** Runs `effect` a year from now, when every link made today has expired. */ +const afterLinksExpire = (effect: Effect.Effect) => + Effect.gen(function* () { + const clock = yield* Clock.Clock; + const ahead = Duration.days(365); + const later = () => clock.currentTimeMillisUnsafe() + Duration.toMillis(ahead); + const laterNanos = () => clock.currentTimeNanosUnsafe() + Duration.toNanosUnsafe(ahead); + return yield* effect.pipe( + Effect.provideService(Clock.Clock, { + currentTimeMillisUnsafe: later, + currentTimeMillis: Effect.sync(later), + currentTimeNanosUnsafe: laterNanos, + currentTimeNanos: Effect.sync(laterNanos), + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), + monotonicTimeNanos: clock.monotonicTimeNanos, + sleep: (duration) => clock.sleep(duration), + }), + ); + }); + const withBoth = (body: (a: Laptop, b: ServedPeer) => Effect.Effect) => Effect.scoped( Effect.gen(function* () { @@ -701,6 +724,29 @@ it.live("naming a machine that is already linked returns the link at once, with ), ); +it.live("a link that expired goes through the card, so the user can link it again", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* linkTo(a.links, b, "read-only"); + const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire); + expect(asked.structuredContent).toMatchObject({ status: "pending" }); + const card = yield* pendingCard(a); + + // Keeping the expired link is no answer: the card fails and says why. + yield* a.requests + .answer({ + threadId, + turnItemId: card.id, + answer: { type: "use-existing", environmentId: box.environmentId }, + }) + .pipe(afterLinksExpire); + expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" }); + expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired"); + }), + ), +); + it.live( "a card for a machine named by id keeps it, and the user may keep a link it already has", () => diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts index b4a52745415f..4f4512fe5278 100644 --- a/apps/server/src/peer/PeerLinkRequests.ts +++ b/apps/server/src/peer/PeerLinkRequests.ts @@ -18,6 +18,7 @@ */ import { CommandId, + type EnvironmentId, MessageId, type NodeId, type OrchestrationV2Notification, @@ -35,6 +36,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -111,6 +113,17 @@ const make = Effect.gen(function* () { }), ); + /** + * The stored link to `environmentId`, or nothing once it has expired: an + * expired link needs a new pairing code, which only the card asks for. + */ + const usableLink = (environmentId: EnvironmentId) => + Effect.all([peerLinks.get(environmentId), DateTime.now]).pipe( + Effect.map(([linked, now]) => + Option.filter(linked, (link) => DateTime.isGreaterThan(link.expiresAt, now)), + ), + ); + const record = ( card: LinkRequestAsk, outcome: LinkRequestOutcome, @@ -156,14 +169,12 @@ const make = Effect.gen(function* () { } // A machine already linked needs no card: the agent can use it now. if (input.environmentId !== undefined) { - const linked = yield* peerLinks - .get(input.environmentId) - .pipe( - Effect.mapError( - (error) => - new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), - ), - ); + const linked = yield* usableLink(input.environmentId).pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), + ), + ); if (Option.isSome(linked)) { return { status: "linked", @@ -251,14 +262,15 @@ const make = Effect.gen(function* () { case "decline": return Effect.succeed({ linkStatus: "declined" }); case "use-existing": - return peerLinks.get(answer.environmentId).pipe( + return usableLink(answer.environmentId).pipe( Effect.flatMap( Option.match({ onNone: () => Effect.fail( new PeerLinkError({ reason: "unknown_link", - message: "That environment is no longer linked here.", + message: + "That environment is no longer linked here, or its link expired. Link it again.", }), ), onSome: (linked) => Effect.succeed(linkedOutcome(linked)), From 59b552379f8bdf91742c2740176dcbc8f339e102 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:04:59 -0700 Subject: [PATCH 131/408] fix(server): a link card stays answerable after a steer, and Stop shows no new one The link_request.record command required the run's current root node on every update. A steer that restarts the turn moves the root, so an answer recorded after it was refused once the link had already been made: the card stayed pending, the agent never heard back, and each retry paired again. The root and a live, unstopped run are now required only when a card is created; an update keeps the card's own node and provider turn. The same check closes a race with Stop: a request that read an active run before thread.stop closed the thread's cards could still record a new pending card, which would wake the agent when answered. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 40 ++++++- apps/server/src/peer/PeerLinkRequests.test.ts | 110 ++++++++++++++++++ 2 files changed, 145 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6bd0f5199cd2..938eff2475f3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8032,11 +8032,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); const run = projection.runs.find((candidate) => candidate.id === command.runId); - if (run === undefined || run.rootNodeId !== command.nodeId) { + if (run === undefined) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`, + cause: `Run ${command.runId} was not found.`, }); } const existing = projection.turnItems.find((item) => item.id === command.turnItemId); @@ -8054,6 +8054,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Link request ${command.turnItemId} belongs to another run.`, }); } + // Only a new card needs its run's current root and a live run. An answer + // may land long after a steer restarted the run or the run ended, and the + // link it reports is already made. + if (existing === undefined && run.rootNodeId !== command.nodeId) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`, + }); + } + if ( + existing === undefined && + (!isBlockingRun(run) || (yield* stopReachedRun(command, command.threadId, run.id))) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not active.`, + }); + } + const nodeId = existing?.nodeId ?? command.nodeId; const now = yield* DateTime.now; // A request is answered once, and a retry finds its card as it was // asked: either one records the card unchanged. @@ -8073,8 +8094,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { ...fields, id: command.turnItemId, - providerThreadId: run.providerThreadId, - providerTurnId: providerTurnForRun(projection, run)?.id ?? null, + // An update keeps where the card was asked, even after a restart. + ...(existing === undefined + ? { + providerThreadId: run.providerThreadId, + providerTurnId: providerTurnForRun(projection, run)?.id ?? null, + } + : { + nodeId: existing.nodeId, + providerThreadId: existing.providerThreadId, + providerTurnId: existing.providerTurnId, + }), nativeItemRef: null, parentItemId: null, ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)), @@ -8098,7 +8128,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "turn-item.updated", threadId: command.threadId, runId: command.runId, - nodeId: command.nodeId, + nodeId, providerInstanceId: run.providerInstanceId, occurredAt: now, payload: turnItem, diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index 6b671b2cdc26..fcb396e8cc65 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -14,6 +14,7 @@ import { type RuntimeMode, RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Clock from "effect/Clock"; @@ -344,6 +345,55 @@ const endRun = (a: Laptop) => }); }); +/** A steer restarts the agent's turn: its run gets a new root node. */ +const restartRun = (a: Laptop) => + Effect.gen(function* () { + const projection = yield* a.orchestrator.getThreadProjection(threadId); + const run = projection.runs.find((candidate) => candidate.id === runId)!; + const node = projection.nodes.find((candidate) => candidate.id === rootNode)!; + const restarted = NodeId.make("node:laptop:root:2"); + const now = yield* DateTime.now; + yield* a.sink.write({ + commandId: CommandId.make("command:restart-run:laptop"), + events: [ + { + id: EventId.make("event:restart-node"), + type: "node.updated", + threadId, + runId, + nodeId: restarted, + driver, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...node, id: restarted, rootNodeId: restarted, startedAt: now }, + }, + { + id: EventId.make("event:restart-run"), + type: "run.updated", + threadId, + runId, + nodeId: restarted, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...run, rootNodeId: restarted }, + }, + ], + }); + }); + +/** What `request` records for a new card, as if it read the run before anything changed. */ +const recordPendingCard = (a: Laptop, key: string) => + a.orchestrator.dispatch({ + type: "link_request.record", + commandId: CommandId.make(`command:pending:${key}`), + threadId, + runId, + nodeId: rootNode, + turnItemId: TurnItemId.make(`turn-item:link-request:${key}`), + reason: "", + linkStatus: "pending", + }); + /** * Every row of every table in the laptop's database, as text, to scan for * anything leaked: events, projections, receipts and outbox alike. @@ -593,6 +643,66 @@ it.live("stopping the thread closes its open card, which then takes no answer", ), ); +it.live("a request that read the run before Stop shows no card once Stop lands", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* a.call({ url: b.url }); + const open = yield* pendingCard(a); + yield* a.orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("command:stop:laptop"), + threadId, + }); + const late = yield* recordPendingCard(a, "after-stop").pipe(Effect.flip); + expect(String(late.cause)).toContain("not active"); + const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter( + (item) => item.type === "link_request", + ); + expect(cards.map((card) => card.id)).toEqual([open.id]); + }), + ), +); + +it.live("a card shows up only while its run is going, and takes an answer after", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* a.call({ url: b.url }); + const card = yield* pendingCard(a); + yield* endRun(a); + const late = yield* recordPendingCard(a, "after-end").pipe(Effect.flip); + expect(String(late.cause)).toContain("not active"); + yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } }); + expect(yield* cardOf(a)).toMatchObject({ linkStatus: "declined" }); + }), + ), +); + +it.live("a steer that restarts the turn leaves its open card answerable", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* a.call({ url: b.url }); + const card = yield* pendingCard(a); + yield* restartRun(a); + const pairing = yield* b.auth.issuePairingCredential(); + yield* a.requests.answer({ + threadId, + turnItemId: card.id, + answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential }, + }); + // The card keeps the node it was asked from, and the agent hears the answer. + expect(yield* cardOf(a)).toMatchObject({ + linkStatus: "linked", + nodeId: rootNode, + linkedEnvironmentId: box.environmentId, + }); + expect((yield* outcomeMessages(a)).messages).toHaveLength(1); + }), + ), +); + it.live("archiving the thread closes its open card", () => withBoth((a, b) => Effect.gen(function* () { From 32ce3bebb111bbe80e396472fafa574983b0f22b Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:20:17 -0700 Subject: [PATCH 132/408] fix(server): a slow machine no longer holds up every link card's answer Answering a link card took one environment-wide lock and held it across PeerLinks.link, which calls the other machine. A peer that was slow to answer blocked every other card's answer until it timed out. The lock is now per card, through the shared KeyedLock, which is all that keeps two answers to one card from both linking. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/PeerLinkRequests.test.ts | 71 +++++++++++++++++++ apps/server/src/peer/PeerLinkRequests.ts | 12 ++-- 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index fcb396e8cc65..f4a231dea1ab 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -20,8 +20,12 @@ import { expect, it } from "@effect/vitest"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as HttpServer from "effect/http/HttpServer"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -703,6 +707,73 @@ it.live("a steer that restarts the turn leaves its open card answerable", () => ), ); +it.live("a slow machine holds up only its own card's answer", () => + withBoth((a, b) => + Effect.scoped( + Effect.gen(function* () { + // A machine that takes the descriptor request and answers when the test says. + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const slow = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); + const server = Context.get(slow, HttpServer.HttpServer); + yield* server.serve( + Deferred.succeed(reached, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(HttpServerResponse.empty({ status: 404 })), + ), + ); + if (server.address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP"); + const slowUrl = `http://127.0.0.1:${server.address.port}`; + + yield* seedThread(a); + // Recorded directly: asking would probe the slow machine before the answer does. + const slowCard = { id: TurnItemId.make("turn-item:link-request:slow") }; + yield* a.orchestrator.dispatch({ + type: "link_request.record", + commandId: CommandId.make("command:pending:slow"), + threadId, + runId, + nodeId: rootNode, + turnItemId: slowCard.id, + url: slowUrl, + reason: "", + linkStatus: "pending", + }); + yield* a.call({ url: b.url, clientRequestId: "box" }); + const boxCard = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find( + (item) => item.type === "link_request" && item.url === b.url, + )!; + + const slowAnswer = yield* a.requests + .answer({ + threadId, + turnItemId: slowCard.id, + answer: { type: "link", urls: [slowUrl], access: "auto", pairingCode: "code" }, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(reached); + + // While the slow machine holds its card, the user answers the other one. + yield* a.requests.answer({ threadId, turnItemId: boxCard.id, answer: { type: "decline" } }); + const items = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems; + expect(items.find((item) => item.id === boxCard.id)).toMatchObject({ + linkStatus: "declined", + }); + expect(items.find((item) => item.id === slowCard.id)).toMatchObject({ + linkStatus: "pending", + }); + + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(slowAnswer); + const failed = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find( + (item) => item.id === slowCard.id, + ); + expect(failed).toMatchObject({ linkStatus: "failed" }); + }), + ), + ), +); + it.live("archiving the thread closes its open card", () => withBoth((a, b) => Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts index 4f4512fe5278..a932a0630bbd 100644 --- a/apps/server/src/peer/PeerLinkRequests.ts +++ b/apps/server/src/peer/PeerLinkRequests.ts @@ -40,7 +40,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Semaphore from "effect/Semaphore"; +import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; @@ -303,8 +303,9 @@ const make = Effect.gen(function* () { } }; - // One answer at a time: two answers racing on one card must not both link. - const answerLock = yield* Semaphore.make(1); + // One answer per card at a time: two answers racing on one card must not + // both link. Other cards go on while a slow peer holds one. + const answerLocks = yield* KeyedLock.make(); const answer: PeerLinkRequests["Service"]["answer"] = (input) => Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ @@ -336,7 +337,10 @@ const make = Effect.gen(function* () { ).pipe( Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })), ); - }).pipe(answerLock.withPermits(1), Effect.withSpan("PeerLinkRequests.answer")); + }).pipe( + (effect) => answerLocks.withLock(input.turnItemId, effect), + Effect.withSpan("PeerLinkRequests.answer"), + ); return PeerLinkRequests.of({ request, answer }); }); From 0434098e9de21dc0af938900c57b9a8ea178f60c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:21:55 -0700 Subject: [PATCH 133/408] fix(web): the link dialog starts fresh each time it opens A successful answer and Cancel closed the dialog without the reset the dialog's own close ran, so reopening it showed the last step, machine, address, access, error and pairing code. Every close now goes through one function that resets; a close while linking is still refused. Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/LinkRequestCard.tsx | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx index 52dc9a62e0ab..6cf580bc7dd9 100644 --- a/apps/web/src/components/chat/LinkRequestCard.tsx +++ b/apps/web/src/components/chat/LinkRequestCard.tsx @@ -262,6 +262,12 @@ function LinkRequestDialog(props: { setError(null); }; + // Every close resets, so a reopened dialog never shows the last answer or its pairing code. + const close = () => { + props.onOpenChange(false); + reset(); + }; + const submit = async () => { if (inFlight.current || target.kind === "none") return; inFlight.current = true; @@ -299,8 +305,7 @@ function LinkRequestDialog(props: { const result = await answer({ environmentId: props.environmentId, input }); if (result._tag === "Success") { // The card switches to its answered row once the item updates. - setPairingCode(""); - props.onOpenChange(false); + close(); return; } if (!isAtomCommandInterrupted(result)) { @@ -321,8 +326,8 @@ function LinkRequestDialog(props: { onOpenChange={(next) => { // An answer that lands after a close would still link, and would close a reopened dialog. if (!next && busy) return; - props.onOpenChange(next); - if (!next) reset(); + if (next) props.onOpenChange(true); + else close(); }} > @@ -441,12 +446,7 @@ function LinkRequestDialog(props: { Back ) : ( - )} From fd3a228efefdcd51831c610bfd58976cdbc6031d Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:24:44 -0700 Subject: [PATCH 134/408] fix(web,mobile): each link answer mints its own pairing code The mint went through one atom per environment, refreshed and then read on every call, so two overlapping answers could both receive the same one-use code and one link failed with the code already spent. Minting now runs as an environment command, which builds a fresh effect for every call, shared by web and mobile through client-runtime. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/state/peerPairingCode.ts | 41 ++++--------------- apps/web/src/state/peerPairingCode.ts | 41 ++++--------------- .../src/state/peerPairingCode.ts | 32 ++++++++++++++- 3 files changed, 49 insertions(+), 65 deletions(-) diff --git a/apps/mobile/src/state/peerPairingCode.ts b/apps/mobile/src/state/peerPairingCode.ts index 6aea8e4bfaa5..789278078bff 100644 --- a/apps/mobile/src/state/peerPairingCode.ts +++ b/apps/mobile/src/state/peerPairingCode.ts @@ -1,42 +1,19 @@ -import { mintPeerPairingCode } from "@t3tools/client-runtime/state/peerPairingCode"; +import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import { Atom, AtomRegistry } from "effect/reactivity"; import { connectionAtomRuntime } from "../connection/runtime"; import { appAtomRegistry } from "./atom-registry"; -import { environmentSession } from "./session"; -// Each read mints a new one-use code; nothing keeps one once it is read. -const peerPairingCodeAtom = Atom.family((environmentId: EnvironmentId) => - connectionAtomRuntime - .atom((get) => { - const prepared = Option.getOrNull( - get(environmentSession.preparedConnectionValueAtom(environmentId)), - ); - if (prepared === null) return Effect.never; - return mintPeerPairingCode(prepared); - }) - .pipe(Atom.withLabel(`mobile-peer-pairing-code:${environmentId}`)), -); +const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime); /** * A fresh pairing code minted on `environmentId` with this client's session - * there, for answering a link request. Fails with `PeerPairingCodeError` when - * the session may not create one. + * there, for answering a link request. Rejects with `PeerPairingCodeError` + * when the session may not create one. */ -export function mintPairingCodeOn(environmentId: EnvironmentId): Promise { - const atom = peerPairingCodeAtom(environmentId); - appAtomRegistry.refresh(atom); - return Effect.runPromise( - Effect.scoped( - Effect.gen(function* () { - yield* AtomRegistry.mount(appAtomRegistry, atom); - return yield* AtomRegistry.getResult(appAtomRegistry, atom, { - suspendOnWaiting: true, - }).pipe(Effect.timeout("15 seconds")); - }), - ), - ); +export async function mintPairingCodeOn(environmentId: EnvironmentId): Promise { + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: undefined }); + if (result._tag === "Success") return result.value; + throw squashAtomCommandFailure(result); } diff --git a/apps/web/src/state/peerPairingCode.ts b/apps/web/src/state/peerPairingCode.ts index dc3afa7b3ff5..9e3fa1fe5434 100644 --- a/apps/web/src/state/peerPairingCode.ts +++ b/apps/web/src/state/peerPairingCode.ts @@ -1,42 +1,19 @@ -import { mintPeerPairingCode } from "@t3tools/client-runtime/state/peerPairingCode"; +import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import { Atom, AtomRegistry } from "effect/reactivity"; import { connectionAtomRuntime } from "../connection/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { environmentSession } from "./session"; -// Each read mints a new one-use code; nothing keeps one once it is read. -const peerPairingCodeAtom = Atom.family((environmentId: EnvironmentId) => - connectionAtomRuntime - .atom((get) => { - const prepared = Option.getOrNull( - get(environmentSession.preparedConnectionValueAtom(environmentId)), - ); - if (prepared === null) return Effect.never; - return mintPeerPairingCode(prepared); - }) - .pipe(Atom.withLabel(`peer-pairing-code:${environmentId}`)), -); +const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime); /** * A fresh pairing code minted on `environmentId` with this client's session - * there, for answering a link request. Fails with `PeerPairingCodeError` when - * the session may not create one. + * there, for answering a link request. Rejects with `PeerPairingCodeError` + * when the session may not create one. */ -export function mintPairingCodeOn(environmentId: EnvironmentId): Promise { - const atom = peerPairingCodeAtom(environmentId); - appAtomRegistry.refresh(atom); - return Effect.runPromise( - Effect.scoped( - Effect.gen(function* () { - yield* AtomRegistry.mount(appAtomRegistry, atom); - return yield* AtomRegistry.getResult(appAtomRegistry, atom, { - suspendOnWaiting: true, - }).pipe(Effect.timeout("15 seconds")); - }), - ), - ); +export async function mintPairingCodeOn(environmentId: EnvironmentId): Promise { + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: undefined }); + if (result._tag === "Success") return result.value; + throw squashAtomCommandFailure(result); } diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts index 0799c1cd7115..a9d5ee9cabdb 100644 --- a/packages/client-runtime/src/state/peerPairingCode.ts +++ b/packages/client-runtime/src/state/peerPairingCode.ts @@ -12,11 +12,17 @@ import { import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import type * as HttpClient from "effect/http/HttpClient"; +import * as Option from "effect/Option"; +import type { Atom } from "effect/reactivity"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; import type { PreparedConnection } from "../connection/model.ts"; +import type { EnvironmentRegistry } from "../connection/registry.ts"; +import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as ManagedRelay from "../relay/managedRelay.ts"; import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts"; +import { createEnvironmentCommand } from "./runtime.ts"; const MINT_TIMEOUT_MS = 8_000; const PEER_PAIRING_CODE_LABEL = "T3 Code link"; @@ -38,7 +44,7 @@ export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError } } -export const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* ( +const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* ( prepared: PreparedConnection, ): Effect.fn.Return { const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner); @@ -73,3 +79,27 @@ export const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairin ); return minted.credential; }); + +/** + * Mints a code on the environment it runs in. Each run mints its own: a code + * is one-use, so two overlapping answers must never share one. + */ +export function createPeerPairingCodeCommand( + runtime: Atom.AtomRuntime, +) { + return createEnvironmentCommand(runtime, { + label: "environment-data:peer-pairing-code:mint", + execute: (_input: void) => + Effect.gen(function* () { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const prepared = yield* SubscriptionRef.get(supervisor.prepared); + if (Option.isNone(prepared)) { + return yield* new PeerPairingCodeError({ + reason: "unavailable", + cause: "The environment is not connected.", + }); + } + return yield* mintPeerPairingCode(prepared.value); + }), + }); +} From 6eaab59c972fedd10744f65cd7dfa530dc5f1f91 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:40:33 -0700 Subject: [PATCH 135/408] fix(server): a thread waits on its link card after the agent's turn ends A waiting link card counted as the thread asking for input only while its run was live. The agent asks without waiting, so its run usually completes first, and the thread then read as done, could auto-settle, and dropped out of the user's inbox while the card still waited for them. A waiting link card now counts until it is answered or closed; a secret card still counts only while its agent waits in the run. The shell query reads it through a new partial index, so finished history is never scanned, and auto-settlement skips a thread with a waiting link card. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/ProjectionStore.ts | 49 +++++++++++++++---- apps/server/src/peer/PeerLinkRequests.test.ts | 12 ++++- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/070_WaitingLinkRequestIndex.ts | 13 +++++ .../reconcileV2PreviewMigration.test.ts | 2 + 5 files changed, 67 insertions(+), 11 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/070_WaitingLinkRequestIndex.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index b9e6e6e9c1bf..318f8865573c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1083,6 +1083,7 @@ type ShellThreadRow = { readonly blocking_failure_payload_json: string | null; readonly pending_request_payload_json: string | null; readonly pending_secret_request_payload_json: string | null; + readonly pending_link_request_payload_json: string | null; readonly latest_user_message_at: string | null; readonly latest_user_authored_message_at: string | null; readonly has_actionable_proposed_plan: number; @@ -1514,6 +1515,14 @@ function secretRequestAsPendingInput( }; } +/** + * A secret card is answered while its agent waits in the run. A link card's + * agent asked without waiting, so the card waits on the user after its run. + */ +const waitsOnUser = (item: OrchestrationV2TurnItem, liveRunIds: ReadonlySet) => + item.type === "link_request" || + (item.type === "secret_request" && item.runId !== null && liveRunIds.has(item.runId)); + export function threadShellFromProjection( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadShell { @@ -1551,13 +1560,7 @@ export function threadShellFromProjection( pendingRuntimeRequest = secretRequestAsPendingInput( projection.turnItems - .filter( - (item) => - (item.type === "secret_request" || item.type === "link_request") && - item.status === "waiting" && - item.runId !== null && - liveRunIds.has(item.runId), - ) + .filter((item) => item.status === "waiting" && waitsOnUser(item, liveRunIds)) .toSorted( (left, right) => DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), @@ -5759,10 +5762,19 @@ export const layer: Layer.Layer = WHERE r.thread_id = t.thread_id AND r.status IN ('preparing', 'starting', 'running', 'waiting') AND secret.thread_id = t.thread_id AND secret.run_id = r.run_id - AND secret.type IN ('secret_request', 'link_request') AND secret.status = 'waiting' + AND secret.type = 'secret_request' AND secret.status = 'waiting' ORDER BY secret.updated_at DESC, secret.turn_item_id DESC LIMIT 1 ) AS pending_secret_request_payload_json, + ( + SELECT link.payload_json + FROM orchestration_v2_projection_turn_items link + INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx + WHERE link.thread_id = t.thread_id + AND link.type = 'link_request' AND link.status = 'waiting' + ORDER BY link.updated_at DESC, link.turn_item_id DESC + LIMIT 1 + ) AS pending_link_request_payload_json, ( SELECT message.updated_at FROM orchestration_v2_projection_messages message @@ -6039,6 +6051,12 @@ export const layer: Layer.Layer = SELECT 1 FROM orchestration_v2_projection_runtime_requests request WHERE request.thread_id = t.thread_id AND request.status = 'pending' ) + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_turn_items link + INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx + WHERE link.thread_id = t.thread_id + AND link.type = 'link_request' AND link.status = 'waiting' + ) ORDER BY t.updated_at ASC, t.thread_id ASC `; if (rows.length === 0) return []; @@ -6197,6 +6215,14 @@ export const layer: Layer.Layer = pendingTurnItemsByThreadId, } = input; const thread = yield* decodeThreadPayload(row.payload_json); + const waitingCards = [ + row.pending_secret_request_payload_json === null + ? null + : yield* decodeTurnItemPayload(row.pending_secret_request_payload_json), + row.pending_link_request_payload_json === null + ? null + : yield* decodeTurnItemPayload(row.pending_link_request_payload_json), + ].filter((item) => item !== null); let pendingRuntimeRequest = row.pending_request_payload_json !== null ? pendingRuntimeRequestSummary( @@ -6205,11 +6231,14 @@ export const layer: Layer.Layer = : null; if ( (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) && - row.pending_secret_request_payload_json !== null + waitingCards.length > 0 ) { pendingRuntimeRequest = secretRequestAsPendingInput( - yield* decodeTurnItemPayload(row.pending_secret_request_payload_json), + waitingCards.toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + )[0] ?? null, ) ?? pendingRuntimeRequest; } let terminalFailureItem = diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index f4a231dea1ab..5ec7aff82b46 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -181,6 +181,7 @@ const makeLaptop = Effect.gen(function* () { requests: Context.get(here, PeerLinkRequests.PeerLinkRequests), orchestrator: Context.get(here, Orchestrator.OrchestratorV2), sink: Context.get(here, EventSink.EventSinkV2), + projections: Context.get(here, ProjectionStore.ProjectionStoreV2), sql: Context.get(database, SqlClient.SqlClient), call: (args: Record, callScope = scope) => server @@ -480,9 +481,18 @@ it.live("the agent asks without waiting, and the user links the box after its tu { kind: "user_input" }, ); - // The agent ends its turn; the card stays answerable. + // The agent ends its turn; the card stays answerable, and the thread still asks. yield* endRun(a); expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" }); + expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject( + { kind: "user_input" }, + ); + expect( + ProjectionStore.threadShellFromProjection( + yield* a.orchestrator.getThreadProjection(threadId), + ).pendingRuntimeRequest, + ).toMatchObject({ kind: "user_input" }); + expect(yield* a.projections.getSettlementCandidates(threadId)).toEqual([]); // The user's client mints a code on the box and picks more than the agent suggested. const pairing = yield* b.auth.issuePairingCredential(); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index addccd7e331b..443ba8d7fb0d 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -72,6 +72,7 @@ import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts" import Migration0067 from "./Migrations/067_WebhookDedupe.ts"; import Migration0068 from "./Migrations/068_PeerLinks.ts"; import Migration0069 from "./Migrations/069_PeerLinkFence.ts"; +import Migration0070 from "./Migrations/070_WaitingLinkRequestIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -144,6 +145,7 @@ const migrationEntries = [ [67, "WebhookDedupe", Migration0067], [68, "PeerLinks", Migration0068], [69, "PeerLinkFence", Migration0069], + [70, "WaitingLinkRequestIndex", Migration0070], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/070_WaitingLinkRequestIndex.ts b/apps/server/src/persistence/Migrations/070_WaitingLinkRequestIndex.ts new file mode 100644 index 000000000000..e025a00d49ba --- /dev/null +++ b/apps/server/src/persistence/Migrations/070_WaitingLinkRequestIndex.ts @@ -0,0 +1,13 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this predicate aligned with ProjectionStore's waiting link card query. + yield* sql` + CREATE INDEX orchestration_v2_projection_turn_items_waiting_link_idx + ON orchestration_v2_projection_turn_items(thread_id, updated_at DESC, turn_item_id DESC) + WHERE type = 'link_request' AND status = 'waiting' + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 24008dcc98a4..cf965b9adcef 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -49,6 +49,7 @@ describe("V2 preview upgrade", () => { [67, "WebhookDedupe"], [68, "PeerLinks"], [69, "PeerLinkFence"], + [70, "WaitingLinkRequestIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -141,6 +142,7 @@ describe("V2 preview upgrade", () => { [67, "WebhookDedupe"], [68, "PeerLinks"], [69, "PeerLinkFence"], + [70, "WaitingLinkRequestIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 6d447b8f7d991a463fa1beba8c686f4a5f43f4b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:06:17 -0700 Subject: [PATCH 136/408] feat(web,mobile): pick a T3 Connect machine when linking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Linking asked for the other machine's address by hand unless an agent asked first. Settings → Linked environments now opens on a machine dropdown, and both it and the agent's link card list the machines on the user's T3 Connect account next to the saved ones, at their Connect address. When this client may mint a pairing code there it does; when it can't (a Connect-only machine, or a session without access:write), it asks for a code but no longer for the address. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/LinkRequestCard.tsx | 90 +++++----- apps/mobile/src/state/peerLinks.ts | 27 +-- apps/mobile/src/state/peerPairingCode.ts | 14 +- .../src/components/chat/LinkRequestCard.tsx | 102 +++++------ .../components/settings/LinkMachineSelect.tsx | 87 +++++++++ .../settings/LinkedEnvironmentsSettings.tsx | 167 ++++++++++++++---- apps/web/src/state/peerLinks.ts | 26 ++- apps/web/src/state/peerPairingCode.ts | 14 +- docs/user/remote-access.md | 14 +- .../client-runtime/src/linkRequest.test.ts | 92 +++++++++- packages/client-runtime/src/linkRequest.ts | 49 +++-- 11 files changed, 497 insertions(+), 185 deletions(-) create mode 100644 apps/web/src/components/settings/LinkMachineSelect.tsx diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx index 5847e94a9e6f..03b2f3ba02d1 100644 --- a/apps/mobile/src/features/threads/LinkRequestCard.tsx +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -21,6 +21,7 @@ import { type OrchestrationV2ProjectedTurnItem, } from "@t3tools/contracts"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import { useMemo, useRef, useState } from "react"; import { Modal, Platform, Pressable, ScrollView, View, type ColorValue } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -266,52 +267,51 @@ function LinkRequestSheet(props: { (useExisting || ((!needsAddress || address.trim().length > 0) && (canMint || pairingCode.trim().length > 0))); + const prepareAnswer = async () => { + if (target.kind === "none") return null; + if (target.kind === "machine" && target.linked) { + return linkRequestAnswerInput(item, { + type: "use-existing", + environmentId: target.environmentId, + }); + } + let code = pairingCode; + if (canMint && targetId !== null) { + const minted = await mintPairingCodeOn(targetId); + if (Result.isFailure(minted)) { + setMintFailed((failed) => new Set(failed).add(targetId)); + setError(linkRequestFailureMessage(minted.failure)); + return null; + } + code = minted.success; + } + return linkRequestAnswerInput(item, { + type: "link", + target: + target.kind === "address" + ? { url: address } + : { ...target, urls: needsAddress ? [address.trim()] : target.urls }, + access, + pairingCode: code, + }); + }; + const submit = async () => { if (inFlight.current || target.kind === "none") return; inFlight.current = true; setBusy(true); setError(null); - try { - let input; - if (target.kind === "machine" && target.linked) { - input = linkRequestAnswerInput(item, { - type: "use-existing", - environmentId: target.environmentId, - }); - } else { - let code = pairingCode; - if (canMint && targetId !== null) { - try { - code = await mintPairingCodeOn(targetId); - } catch (cause) { - setMintFailed((failed) => new Set(failed).add(targetId)); - setError(linkRequestFailureMessage(cause)); - return; - } - } - input = linkRequestAnswerInput(item, { - type: "link", - target: - target.kind === "address" - ? { url: address } - : { ...target, urls: needsAddress ? [address.trim()] : target.urls }, - access, - pairingCode: code, - }); - } - if (input === null) return; - const result = await answer({ environmentId: props.environmentId, input }); - if (result._tag === "Success") { - setPairingCode(""); - props.onClose(); - return; - } - if (!isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); - } - } finally { - inFlight.current = false; - setBusy(false); + const input = await prepareAnswer(); + const result = + input === null ? null : await answer({ environmentId: props.environmentId, input }); + inFlight.current = false; + setBusy(false); + if (result === null) return; + if (result._tag === "Success") { + setPairingCode(""); + props.onClose(); + } else if (!isAtomCommandInterrupted(result)) { + setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); } }; @@ -470,7 +470,13 @@ function MachineRow(props: { readonly onPress: () => void; }) { const { machine } = props; - const status = machine.linked ? "Linked" : machine.connected ? null : "Not connected"; + const status = machine.linked + ? "Linked" + : machine.connected + ? null + : machine.connectOnly + ? "T3 Connect" + : "Not connected"; return ( { + if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery(); + }); + useEffect(() => { + if (enabled) discoverIfUnasked(); + }, [enabled]); const links = useEnvironmentQuery( enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null, ); @@ -28,12 +40,7 @@ export function useLinkableMachines(environmentId: EnvironmentId, enabled: boole environments, threadEnvironmentId: environmentId, linkedIds: new Set(links.data?.links.map((link) => link.environmentId)), - connectAddresses: new Map( - [...discovery.environments].map(([id, found]) => [ - id, - found.environment.endpoint.httpBaseUrl, - ]), - ), + connect: discovery.environments, }), [discovery.environments, environmentId, environments, links.data], ); diff --git a/apps/mobile/src/state/peerPairingCode.ts b/apps/mobile/src/state/peerPairingCode.ts index 789278078bff..2d2d3de20c1a 100644 --- a/apps/mobile/src/state/peerPairingCode.ts +++ b/apps/mobile/src/state/peerPairingCode.ts @@ -1,6 +1,7 @@ import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; +import * as Result from "effect/Result"; import { connectionAtomRuntime } from "../connection/runtime"; import { appAtomRegistry } from "./atom-registry"; @@ -9,11 +10,14 @@ const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime); /** * A fresh pairing code minted on `environmentId` with this client's session - * there, for answering a link request. Rejects with `PeerPairingCodeError` - * when the session may not create one. + * there, for answering a link request. Fails with `PeerPairingCodeError` when + * the session may not create one. */ -export async function mintPairingCodeOn(environmentId: EnvironmentId): Promise { +export async function mintPairingCodeOn( + environmentId: EnvironmentId, +): Promise> { const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: undefined }); - if (result._tag === "Success") return result.value; - throw squashAtomCommandFailure(result); + return result._tag === "Success" + ? Result.succeed(result.value) + : Result.fail(squashAtomCommandFailure(result)); } diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx index 6cf580bc7dd9..a7e5dde46658 100644 --- a/apps/web/src/components/chat/LinkRequestCard.tsx +++ b/apps/web/src/components/chat/LinkRequestCard.tsx @@ -21,8 +21,9 @@ import { type OrchestrationV2ProjectedTurnItem, } from "@t3tools/contracts"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import { CheckIcon, LinkIcon, MinusIcon, XIcon } from "lucide-react"; -import { useId, useMemo, useRef, useState } from "react"; +import { useId, useRef, useState } from "react"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; import { mintPairingCodeOn } from "../../state/peerPairingCode"; @@ -32,7 +33,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { accessConfig } from "../auth/ConnectAgentSurface"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { LinkAccessPicker } from "../settings/LinkAccessPicker"; -import { Badge } from "../ui/badge"; +import { ANOTHER_ADDRESS, LinkMachineBadge } from "../settings/LinkMachineSelect"; import { Button } from "../ui/button"; import { Dialog } from "../ui/dialog"; import { Input } from "../ui/input"; @@ -42,9 +43,6 @@ import { WorkLogRow } from "./WorkLog"; const accessLabel = (access: AuthMcpClientAccess) => accessConfig[access].label; -/** The machine list's row for linking by an address typed in. */ -const ANOTHER_ADDRESS = "another-address"; - /** Whether the agent left the machine for the user to pick. */ const picksMachine = (item: LinkRequestItem) => item.environmentId === undefined && item.url === undefined; @@ -211,7 +209,7 @@ function LinkRequestDialog(props: { const formId = useId(); const pickMachine = picksMachine(item); const listed = useLinkableMachines(props.environmentId, props.open); - const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]); + const machines = rankMachinesByHint(listed, item.hint); // Null until the user picks; until then the hint's best match is picked. const [choice, setChoice] = useState(null); const [address, setAddress] = useState(item.url ?? ""); @@ -268,52 +266,52 @@ function LinkRequestDialog(props: { reset(); }; + // Settles to the answer to send, an error to show, or nothing to do. + const prepareAnswer = async () => { + if (target.kind === "none") return null; + if (target.kind === "machine" && target.linked) { + return linkRequestAnswerInput(item, { + type: "use-existing", + environmentId: target.environmentId, + }); + } + let code = pairingCode; + if (canMint && targetId !== null) { + const minted = await mintPairingCodeOn(targetId); + if (Result.isFailure(minted)) { + setMintFailed((failed) => new Set(failed).add(targetId)); + setError(linkRequestFailureMessage(minted.failure)); + return null; + } + code = minted.success; + } + return linkRequestAnswerInput(item, { + type: "link", + target: + target.kind === "address" + ? { url: address } + : { ...target, urls: needsAddress ? [address.trim()] : target.urls }, + access, + pairingCode: code, + }); + }; + const submit = async () => { if (inFlight.current || target.kind === "none") return; inFlight.current = true; setBusy(true); setError(null); - try { - let input; - if (target.kind === "machine" && target.linked) { - input = linkRequestAnswerInput(item, { - type: "use-existing", - environmentId: target.environmentId, - }); - } else { - let code = pairingCode; - if (canMint && targetId !== null) { - try { - code = await mintPairingCodeOn(targetId); - } catch (cause) { - setMintFailed((failed) => new Set(failed).add(targetId)); - setError(linkRequestFailureMessage(cause)); - return; - } - } - input = linkRequestAnswerInput(item, { - type: "link", - target: - target.kind === "address" - ? { url: address } - : { ...target, urls: needsAddress ? [address.trim()] : target.urls }, - access, - pairingCode: code, - }); - } - if (input === null) return; - const result = await answer({ environmentId: props.environmentId, input }); - if (result._tag === "Success") { - // The card switches to its answered row once the item updates. - close(); - return; - } - if (!isAtomCommandInterrupted(result)) { - setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); - } - } finally { - inFlight.current = false; - setBusy(false); + const input = await prepareAnswer(); + const result = + input === null ? null : await answer({ environmentId: props.environmentId, input }); + inFlight.current = false; + setBusy(false); + if (result === null) return; + if (result._tag === "Success") { + // The card switches to its answered row once the item updates. + close(); + } else if (!isAtomCommandInterrupted(result)) { + setError(linkRequestFailureMessage(squashAtomCommandFailure(result))); } }; @@ -493,15 +491,7 @@ function MachinePicker(props: { className="size-4 shrink-0 text-muted-foreground" /> {machine.label} - {machine.linked ? ( - - Linked - - ) : machine.connected ? null : ( - - Not connected - - )} + ))}
    --pairing-code --access `. You can also ask an agent to link a machine by name, such as "delegate this to -my vps". It shows a card in the thread where you pick the machine from the ones -this app knows (or enter an address) and the access, then approve. If this app -is connected to that machine with a session that manages access there, it uses -that session; otherwise paste a pairing code from that machine's -**Settings → Connections**. +my vps". It shows a card in the thread where you pick the machine the same way +and the access, then approve. - The access you pick is the most agents from this machine may do there. An agent also never gets more there than its own mode here. diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts index 29ec717f9456..1176f77b5ac2 100644 --- a/packages/client-runtime/src/linkRequest.test.ts +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -1,10 +1,12 @@ import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts"; +import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay"; import * as Option from "effect/Option"; import { describe, expect, it } from "vite-plus/test"; import { BearerConnectionProfile } from "./connection/catalog.ts"; import { BearerConnectionTarget, RelayConnectionTarget } from "./connection/model.ts"; import type { EnvironmentPresentation } from "./connection/presentation.ts"; +import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts"; import { linkableMachines, linkRequestAnswerInput, @@ -142,6 +144,45 @@ const presentation = ( }; }; +const discovered = ( + id: string, + label: string, + machine?: "mac-mini", +): RelayDiscoveredEnvironment => ({ + environment: { + environmentId: EnvironmentId.make(id), + label, + endpoint: { + httpBaseUrl: `https://${id}.t3.example`, + wsBaseUrl: `wss://${id}.t3.example`, + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-10-01T00:00:00.000Z", + }, + availability: "online", + status: + machine === undefined + ? Option.none() + : Option.some({ + environmentId: EnvironmentId.make(id), + endpoint: { + httpBaseUrl: `https://${id}.t3.example`, + wsBaseUrl: `wss://${id}.t3.example`, + providerKind: "cloudflare_tunnel", + }, + status: "online", + checkedAt: "2026-10-01T00:00:00.000Z", + descriptor: { + environmentId: EnvironmentId.make(id), + label, + platform: { os: "darwin", arch: "arm64", machine }, + serverVersion: "1.0.0", + capabilities: {}, + }, + } as unknown as RelayEnvironmentStatusResponse), + error: Option.none(), +}); + describe("linkableMachines", () => { it("lists the other machines with reported addresses before saved ones, once each", () => { const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] }); @@ -155,7 +196,7 @@ describe("linkableMachines", () => { environments: [here, vps, mini], threadEnvironmentId: here.environmentId, linkedIds: new Set([mini.environmentId]), - connectAddresses: new Map(), + connect: new Map(), }), ).toEqual([ { @@ -163,6 +204,7 @@ describe("linkableMachines", () => { label: "VPS", machine: "laptop", connected: true, + connectOnly: false, linked: false, urls: ["https://vps.ts.net", "https://vps.example.com"], }, @@ -171,6 +213,7 @@ describe("linkableMachines", () => { label: "Mini", machine: "server", connected: false, + connectOnly: false, linked: true, urls: [], }, @@ -184,19 +227,51 @@ describe("linkableMachines", () => { environments: [here, box], threadEnvironmentId: here.environmentId, linkedIds: new Set(), - connectAddresses: new Map([[box.environmentId, "https://box.t3.example"]]), + connect: new Map([[box.environmentId, discovered(box.environmentId, "Box")]]), }); - expect(listed?.urls).toEqual(["https://box.t3.example"]); + expect(listed?.urls).toEqual(["https://environment-box.t3.example"]); // Until discovery has found it, there is no address to offer. expect( linkableMachines({ environments: [here, box], threadEnvironmentId: here.environmentId, linkedIds: new Set(), - connectAddresses: new Map(), + connect: new Map(), })[0]?.urls, ).toEqual([]); }); + + it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => { + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] }); + const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] }); + const listed = linkableMachines({ + environments: [here, vps], + threadEnvironmentId: here.environmentId, + linkedIds: new Set([EnvironmentId.make("environment-old")]), + connect: new Map([ + // This environment and saved machines are listed once, as saved. + [here.environmentId, discovered(here.environmentId, "Here")], + [vps.environmentId, discovered(vps.environmentId, "VPS")], + ["environment-mini", discovered("environment-mini", "Mac mini", "mac-mini")], + ["environment-old", discovered("environment-old", "Old box")], + ]), + }); + expect(listed.map((machine) => [machine.label, machine.connectOnly])).toEqual([ + ["VPS", false], + ["Mac mini", true], + ["Old box", true], + ]); + expect(listed[1]).toEqual({ + environmentId: EnvironmentId.make("environment-mini"), + label: "Mac mini", + machine: "mac-mini", + connected: false, + connectOnly: true, + linked: false, + urls: ["https://environment-mini.t3.example"], + }); + expect(listed[2]).toMatchObject({ machine: "server", linked: true }); + }); }); describe("rankMachinesByHint", () => { @@ -223,7 +298,14 @@ describe("rankMachinesByHint", () => { { environmentId: EnvironmentId.make("environment-vps"), label: "Hetzner VPS" }, ].map( (machine) => - ({ ...machine, machine: "server", connected: true, linked: false, urls: [] }) as const, + ({ + ...machine, + machine: "server", + connected: true, + connectOnly: false, + linked: false, + urls: [], + }) as const, ); expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps"); // Agents pass the user's words, which name the machine among others. diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts index 58d6cd5a69c0..27e633672231 100644 --- a/packages/client-runtime/src/linkRequest.ts +++ b/packages/client-runtime/src/linkRequest.ts @@ -6,9 +6,11 @@ import { type PeerLinkRequestAnswerInput, resolveEnvironmentMachineKind, } from "@t3tools/contracts"; +import * as Option from "effect/Option"; import type { EnvironmentPresentation } from "./connection/presentation.ts"; import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts"; +import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts"; export type LinkRequestItem = Extract; @@ -27,6 +29,8 @@ export interface LinkableMachine { readonly label: string; readonly machine: EnvironmentMachineKind; readonly connected: boolean; + /** Found on the user's T3 Connect account rather than saved in this client. */ + readonly connectOnly: boolean; /** Whether the thread's environment already has a link to it. */ readonly linked: boolean; /** @@ -40,10 +44,10 @@ export interface LinkableMachine { /** * The machines in the client's catalog other than the thread's own - * environment, in catalog order. `linkedIds` are the environments the thread's - * environment links to already. `connectAddresses` are the T3 Connect - * addresses relay discovery found, by environment id: a server reaches a - * machine there as a browser does, so a Connect route is a usable address. + * environment, in catalog order, then the ones only T3 Connect knows. + * `linkedIds` are the environments the thread's environment links to already. + * `connect` is what relay discovery found, by environment id: a server reaches + * a machine there as a browser does, so its Connect address is a usable one. */ export function linkableMachines(input: { readonly environments: ReadonlyArray< @@ -51,18 +55,20 @@ export function linkableMachines(input: { >; readonly threadEnvironmentId: EnvironmentId; readonly linkedIds: ReadonlySet; - readonly connectAddresses: ReadonlyMap; + readonly connect: ReadonlyMap; }): ReadonlyArray { - return input.environments + const saved = input.environments .filter((environment) => environment.environmentId !== input.threadEnvironmentId) .map((environment) => { const reported = (environment.serverConfig?.directEndpoints ?? []).map( (endpoint) => endpoint.httpBaseUrl, ); - const connect = input.connectAddresses.get(environment.environmentId); - const saved = connectionRoutes(environment.entry).flatMap((route) => { + const connect = input.connect.get(environment.environmentId)?.environment.endpoint; + const routes = connectionRoutes(environment.entry).flatMap((route) => { const url = - route.target._tag === "RelayConnectionTarget" ? connect : routeHttpBaseUrl(route); + route.target._tag === "RelayConnectionTarget" + ? connect?.httpBaseUrl + : routeHttpBaseUrl(route); return url === null || url === undefined ? [] : [url]; }); return { @@ -70,10 +76,33 @@ export function linkableMachines(input: { label: environment.entry.target.label, machine: resolveEnvironmentMachineKind(environment.serverConfig), connected: environment.connection.phase === "connected", + connectOnly: false, linked: input.linkedIds.has(environment.environmentId), - urls: [...new Set([...reported, ...saved])], + urls: [...new Set([...reported, ...routes])], }; }); + const savedIds = new Set(saved.map((machine) => machine.environmentId)); + const connectOnly = [...input.connect.values()] + .filter( + ({ environment }) => + environment.environmentId !== input.threadEnvironmentId && + !savedIds.has(environment.environmentId), + ) + .map(({ environment, status }) => { + const descriptor = Option.getOrUndefined(status)?.descriptor; + return { + environmentId: environment.environmentId, + label: environment.label, + machine: resolveEnvironmentMachineKind( + descriptor === undefined ? null : { environment: descriptor }, + ), + connected: false, + connectOnly: true, + linked: input.linkedIds.has(environment.environmentId), + urls: [environment.endpoint.httpBaseUrl], + }; + }); + return [...saved, ...connectOnly]; } const words = (text: string) => From 71bc8a87e79f3a40b808fe38dfe90a60caf556fb Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:16:56 -0700 Subject: [PATCH 137/408] fix(web,mobile): a minted pairing code carries the access the link asks for The client minted every link code with read and operate only, so linking with full access always failed: the server wants settings and source control too. The access-to-scope mapping moves into contracts, the server checks against it, and the client mints exactly those scopes for the access picked. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/LinkRequestCard.tsx | 2 +- apps/mobile/src/state/peerPairingCode.ts | 9 +- apps/server/src/auth/EnvironmentAuth.ts | 18 +- apps/server/src/auth/McpOAuth.test.ts | 19 ++ apps/server/src/auth/McpOAuth.ts | 7 +- apps/server/src/auth/mcpOAuthHttp.ts | 6 +- .../src/orchestration-v2/Orchestrator.ts | 17 +- apps/server/src/peer/PeerForwarding.ts | 113 +++---- apps/server/src/peer/PeerLinkRequests.ts | 23 +- apps/server/src/peer/PeerLinks.ts | 294 +++++++++--------- .../src/components/chat/LinkRequestCard.tsx | 2 +- .../settings/LinkedEnvironmentsSettings.tsx | 2 +- apps/web/src/state/peerPairingCode.ts | 9 +- .../src/state/peerPairingCode.ts | 42 +-- packages/contracts/src/auth.ts | 13 + 15 files changed, 297 insertions(+), 279 deletions(-) diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx index 03b2f3ba02d1..ef5516b8d095 100644 --- a/apps/mobile/src/features/threads/LinkRequestCard.tsx +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -277,7 +277,7 @@ function LinkRequestSheet(props: { } let code = pairingCode; if (canMint && targetId !== null) { - const minted = await mintPairingCodeOn(targetId); + const minted = await mintPairingCodeOn(targetId, access); if (Result.isFailure(minted)) { setMintFailed((failed) => new Set(failed).add(targetId)); setError(linkRequestFailureMessage(minted.failure)); diff --git a/apps/mobile/src/state/peerPairingCode.ts b/apps/mobile/src/state/peerPairingCode.ts index 2d2d3de20c1a..6cf4c6dc3342 100644 --- a/apps/mobile/src/state/peerPairingCode.ts +++ b/apps/mobile/src/state/peerPairingCode.ts @@ -1,6 +1,6 @@ import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts"; import * as Result from "effect/Result"; import { connectionAtomRuntime } from "../connection/runtime"; @@ -10,13 +10,14 @@ const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime); /** * A fresh pairing code minted on `environmentId` with this client's session - * there, for answering a link request. Fails with `PeerPairingCodeError` when - * the session may not create one. + * there, for linking with `access`. Fails with `PeerPairingCodeError` when the + * session may not create one. */ export async function mintPairingCodeOn( environmentId: EnvironmentId, + access: AuthMcpClientAccess, ): Promise> { - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: undefined }); + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access }); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 995ea24fe71c..91e052466c3a 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -2,9 +2,6 @@ import { AuthAccessTokenType, AuthAccessWriteScope, AuthOrchestrationOperateScope, - AuthOrchestrationReadScope, - AuthSettingsWriteScope, - AuthSourceControlWriteScope, AuthStandardClientScopes, type AuthAccessTokenResult, type AuthBrowserSessionResult, @@ -23,6 +20,7 @@ import { type AuthWebSocketTicketResult, DpopFailureReason, type DpopFailureReason as DpopFailureReasonType, + mcpClientScopes, } from "@t3tools/contracts"; import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; import * as Context from "effect/Context"; @@ -77,20 +75,6 @@ export interface IssuedBearerSession { const MCP_CLIENT_SUBJECT = "mcp-client"; const MCP_CLIENT_SESSION_TTL = Duration.days(30); -export const mcpClientScopes = ( - access: AuthMcpClientAccess, -): ReadonlyArray => - access === "read-only" - ? [AuthOrchestrationReadScope] - : access === "full-access" - ? [ - AuthOrchestrationReadScope, - AuthOrchestrationOperateScope, - AuthSettingsWriteScope, - AuthSourceControlWriteScope, - ] - : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; - export interface McpClientSession { readonly sessionId: AuthSessionId; readonly label: string; diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index 0846056dafe5..5c73cc03fff9 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -1,8 +1,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { + AuthMcpClientAccess, AuthStandardClientScopes, type AuthCreatePairingCredentialInput, EnvironmentHttpApi, + mcpClientScopes, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; @@ -480,6 +482,23 @@ it.live( ), ); +it.live("a code minted with an access level's scopes approves that access", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const params = authorizeParams(yield* registeredClientId(handler)); + for (const access of AuthMcpClientAccess.literals) { + const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] }); + const approval = yield* decide(handler, params, { + _tag: "pairing-code", + access, + code: code.credential, + }); + expect(approval.status, access).toBe(200); + } + }), + ), +); + it.live("one-click approves only access the browser session holds the scopes for", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 454857c8853e..d725f0edde25 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -14,6 +14,7 @@ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope, MCP_PEER_LINK_SOFTWARE_ID, + mcpClientScopes, } from "@t3tools/contracts"; import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; import * as Clock from "effect/Clock"; @@ -446,9 +447,7 @@ const make = Effect.gen(function* () { if ( session === undefined || !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) || - !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) => - session.scopes.includes(scope), - ) + !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope)) ) { return yield* new McpOAuthPageError({ description: "Your session cannot approve this request. Enter a pairing code instead.", @@ -533,7 +532,7 @@ const make = Effect.gen(function* () { access_token: issued.token, token_type: "Bearer", expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)), - scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)), + scope: encodeOAuthScope(mcpClientScopes(pending.access)), }; }, ); diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index d8f2471872e2..6f37d5f7e3f0 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -3,6 +3,7 @@ import { type AuthMcpAuthorizationRequest, AuthMcpClientAccess, EnvironmentHttpApi, + mcpClientScopes, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; @@ -10,7 +11,6 @@ import { HttpServerRequest, HttpServerResponse } from "effect/http"; import * as HttpEffect from "effect/http/HttpEffect"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; -import * as EnvironmentAuth from "./EnvironmentAuth.ts"; import * as McpOAuth from "./McpOAuth.ts"; import { renderErrorPage } from "./mcpOAuthHtml.ts"; @@ -121,9 +121,7 @@ export const layer = HttpApiBuilder.group( : { csrfToken: session.csrfToken, oneClickAccess: AuthMcpClientAccess.literals.filter((access) => - EnvironmentAuth.mcpClientScopes(access).every((scope) => - session.scopes.includes(scope), - ), + mcpClientScopes(access).every((scope) => session.scopes.includes(scope)), ), }), }; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 938eff2475f3..c3aaecbf9ea9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8168,13 +8168,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio * waiting long ago, so nobody is woken: stopping or archiving the thread * means the user is done with it. */ - const closePendingLinkRequests = (input: { - readonly command: OrchestrationV2ServerCommand; - readonly events: Ref.Ref>; - readonly threadId: ThreadId; - readonly now: DateTime.Utc; - }) => - Effect.gen(function* () { + const closePendingLinkRequests = Effect.fn("orchestrationV2.closePendingLinkRequests")( + function* (input: { + readonly command: OrchestrationV2ServerCommand; + readonly events: Ref.Ref>; + readonly threadId: ThreadId; + readonly now: DateTime.Utc; + }) { const { turnItems } = yield* projectionStore .getThreadRecords(input.threadId, ["turnItems"], { turnItemTypes: ["link_request"], @@ -8202,7 +8202,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); } - }); + }, + ); const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")( function* ( diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index 584923c685a6..b5a2cc501894 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -117,38 +117,37 @@ const make = Effect.gen(function* () { ); /** Tool and contract schemas are plain data: they encode and decode without services. */ - const forward = ( + const forward = Effect.fn("PeerForwarding.forward")(function* ( scope: Scope, toolName: string, parameters: Schema.Top, success: Schema.Top, environmentId: EnvironmentId, params: unknown, - ) => - Effect.gen(function* () { - const limits = yield* callerLimits(scope); - const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder)( - params, - ).pipe(Effect.mapError(unavailable))) as Record; - const { environmentId: _target, ...args } = encoded; - // A pending upload lives here, so it cannot go with the call. - if (Array.isArray(args.attachments) && args.attachments.length > 0) { - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: "A launch in a linked environment cannot carry attachments yet.", - }); - } - if (typeof args.clientRequestId === "string") { - args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId); - } - return yield* peers.call({ - environmentId, - tool: toolName, - arguments: args, - limits, - success: success as Schema.Decoder, + ) { + const limits = yield* callerLimits(scope); + const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder)( + params, + ).pipe(Effect.mapError(unavailable))) as Record; + const { environmentId: _target, ...args } = encoded; + // A pending upload lives here, so it cannot go with the call. + if (Array.isArray(args.attachments) && args.attachments.length > 0) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: "A launch in a linked environment cannot carry attachments yet.", }); + } + if (typeof args.clientRequestId === "string") { + args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId); + } + return yield* peers.call({ + environmentId, + tool: toolName, + arguments: args, + limits, + success: success as Schema.Decoder, }); + }); const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) => forward( @@ -174,36 +173,37 @@ const make = Effect.gen(function* () { input, ); - const waitForThread: PeerForwarding["Service"]["waitForThread"] = (scope, environmentId, input) => - Effect.gen(function* () { - let remaining = Math.min( - MAX_WAIT_TIMEOUT_MS, - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn( + "PeerForwarding.waitForThread", + )(function* (scope, environmentId, input) { + let remaining = Math.min( + MAX_WAIT_TIMEOUT_MS, + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + ); + let runId = input.runId; + while (true) { + const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS); + const result = yield* forward( + scope, + "t3_thread_wait", + OrchestratorMcpThreadWaitInput, + OrchestratorMcpThreadWaitResult, + environmentId, + { + threadId: input.threadId, + ...(runId === undefined ? {} : { runId }), + timeoutMs: chunk, + ...(input.untilDelegatedWorkSettled === undefined + ? {} + : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }), + }, ); - let runId = input.runId; - while (true) { - const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS); - const result = yield* forward( - scope, - "t3_thread_wait", - OrchestratorMcpThreadWaitInput, - OrchestratorMcpThreadWaitResult, - environmentId, - { - threadId: input.threadId, - ...(runId === undefined ? {} : { runId }), - timeoutMs: chunk, - ...(input.untilDelegatedWorkSettled === undefined - ? {} - : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }), - }, - ); - remaining -= chunk; - if (!result.timedOut || remaining <= 0) return result; - // Later pieces wait for the run the first one picked, not a newer one. - runId = result.runId ?? undefined; - } - }); + remaining -= chunk; + if (!result.timedOut || remaining <= 0) return result; + // Later pieces wait for the run the first one picked, not a newer one. + runId = result.runId ?? undefined; + } + }); const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) => tool.name === "t3_thread_wait" @@ -221,8 +221,8 @@ const make = Effect.gen(function* () { const NOT_LISTED = "A machine the user means that is not listed here is not linked yet: call t3_environment_link with a hint from their words (or the environmentId of a machine they mentioned), and the user picks it and its access in a card."; - const listLinks: PeerForwarding["Service"]["links"] = (scope) => - Effect.gen(function* () { + const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")( + function* (scope) { yield* callerLimits(scope); const listed = yield* links.list.pipe( Effect.mapError( @@ -242,7 +242,8 @@ const make = Effect.gen(function* () { })), notListed: NOT_LISTED, }; - }); + }, + ); return PeerForwarding.of({ call, diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts index a932a0630bbd..2f78671359a9 100644 --- a/apps/server/src/peer/PeerLinkRequests.ts +++ b/apps/server/src/peer/PeerLinkRequests.ts @@ -147,8 +147,8 @@ const make = Effect.gen(function* () { ...(wake === undefined ? {} : { wake }), }); - const request: PeerLinkRequests["Service"]["request"] = (scope, input) => - Effect.gen(function* () { + const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")( + function* (scope, input) { // The card is shown in, and answered from, the caller's own thread. const threadScope = yield* McpInvocationContext.requireThreadScope( scope, @@ -245,7 +245,9 @@ const make = Effect.gen(function* () { ), ); return pendingResult(turnItemId); - }).pipe(Effect.withSpan("PeerLinkRequests.request")); + }, + Effect.withSpan("PeerLinkRequests.request"), + ); const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({ linkStatus: "linked", @@ -306,8 +308,8 @@ const make = Effect.gen(function* () { // One answer per card at a time: two answers racing on one card must not // both link. Other cards go on while a slow peer holds one. const answerLocks = yield* KeyedLock.make(); - const answer: PeerLinkRequests["Service"]["answer"] = (input) => - Effect.gen(function* () { + const answer: PeerLinkRequests["Service"]["answer"] = Effect.fn("PeerLinkRequests.answer")( + function* (input) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId, "link_request.answer": input.answer.type, @@ -337,10 +339,13 @@ const make = Effect.gen(function* () { ).pipe( Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })), ); - }).pipe( - (effect) => answerLocks.withLock(input.turnItemId, effect), - Effect.withSpan("PeerLinkRequests.answer"), - ); + }, + (effect, input) => + effect.pipe( + (effect) => answerLocks.withLock(input.turnItemId, effect), + Effect.withSpan("PeerLinkRequests.answer"), + ), + ); return PeerLinkRequests.of({ request, answer }); }); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 8fb6767c0f4e..830e958020aa 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -185,20 +185,18 @@ const make = Effect.gen(function* () { Effect.option, ); - const toLink = (row: PeerLinkRow) => - Effect.gen(function* () { - return { - environmentId: EnvironmentId.make(row.environment_id), - label: row.label, - urls: yield* decodeUrls(row.urls_json), - access: yield* decodeAccess(row.access), - linkedAt: DateTime.makeUnsafe(row.linked_at), - expiresAt: DateTime.makeUnsafe(row.expires_at), - lastReachedAt: - row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at), - lastError: row.last_error, - } satisfies PeerLink; - }).pipe(Effect.catch(failStorage)); + const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) { + return { + environmentId: EnvironmentId.make(row.environment_id), + label: row.label, + urls: yield* decodeUrls(row.urls_json), + access: yield* decodeAccess(row.access), + linkedAt: DateTime.makeUnsafe(row.linked_at), + expiresAt: DateTime.makeUnsafe(row.expires_at), + lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at), + lastError: row.last_error, + } satisfies PeerLink; + }, Effect.catch(failStorage)); const readRows = sql` SELECT * FROM peer_environment_links ORDER BY label, environment_id @@ -213,8 +211,8 @@ const make = Effect.gen(function* () { ); /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */ - const signIn = (origin: string, input: PeerLinkCreateInput, clientName: string) => - Effect.gen(function* () { + const signIn = Effect.fn("PeerLinks.signIn")( + function* (origin: string, input: PeerLinkCreateInput, clientName: string) { const client = yield* clientFor(origin); // Only the peer's own refusals are rejections. A dropped connection or // an answer this version cannot read is classified below. @@ -303,132 +301,136 @@ const make = Effect.gen(function* () { ), ), ); - }).pipe( - // Endpoint errors are mapped above; what is left is the transport or an - // answer this version cannot decode. - Effect.catchTags({ - SchemaError: (cause) => - Effect.fail( - new PeerLinkError({ - reason: "incompatible", - message: `${origin} answered in a shape this version does not understand. Update both environments.`, - cause, - }), - ), - HttpClientError: (cause) => - Effect.fail( - new PeerLinkError({ - reason: "unreachable", - message: `${origin} stopped answering while linking.`, - cause, - }), - ), - }), - ); + }, + (effect, origin, input, clientName) => + effect.pipe( + // Endpoint errors are mapped above; what is left is the transport or an + // answer this version cannot decode. + Effect.catchTags({ + SchemaError: (cause) => + Effect.fail( + new PeerLinkError({ + reason: "incompatible", + message: `${origin} answered in a shape this version does not understand. Update both environments.`, + cause, + }), + ), + HttpClientError: (cause) => + Effect.fail( + new PeerLinkError({ + reason: "unreachable", + message: `${origin} stopped answering while linking.`, + cause, + }), + ), + }), + ), + ); /** * The addresses that answer as `environmentId`, in the order given, with * what the first one answered. Addresses this environment would not send * credentials to are skipped; when every one is, the failure says why. */ - const answeringAs = (urls: ReadonlyArray, environmentId: EnvironmentId, name: string) => - Effect.gen(function* () { - const checked = yield* Effect.forEach( - urls, - (url) => - Effect.gen(function* () { - const origin = yield* peerOrigin(url); - return { origin, descriptor: yield* describe(origin) }; - }).pipe(Effect.result), - { concurrency: "unbounded" }, - ); - const matching = checked.flatMap((result) => - Result.isSuccess(result) && - Option.isSome(result.success.descriptor) && - result.success.descriptor.value.environmentId === environmentId - ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }] - : [], + const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* ( + urls: ReadonlyArray, + environmentId: EnvironmentId, + name: string, + ) { + const checked = yield* Effect.forEach( + urls, + (url) => + Effect.gen(function* () { + const origin = yield* peerOrigin(url); + return { origin, descriptor: yield* describe(origin) }; + }).pipe(Effect.result), + { concurrency: "unbounded" }, + ); + const matching = checked.flatMap((result) => + Result.isSuccess(result) && + Option.isSome(result.success.descriptor) && + result.success.descriptor.value.environmentId === environmentId + ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }] + : [], + ); + const first = matching[0]; + if (first === undefined) { + const refusals = checked.flatMap((result) => + Result.isFailure(result) ? [result.failure.message] : [], ); - const first = matching[0]; - if (first === undefined) { - const refusals = checked.flatMap((result) => - Result.isFailure(result) ? [result.failure.message] : [], - ); - return yield* new PeerLinkError({ - reason: "unreachable", - message: - refusals.length === checked.length - ? `This environment could not reach ${name}: ${refusals.join(" ")}` - : `This environment could not reach ${name} at ${urls.join(", ")}.`, - }); - } - // Each address is kept once, even when two spellings share an origin. - const origins = [...new Set(matching.map((found) => found.origin))]; - return { primary: first.origin, peer: first.descriptor, origins }; - }); + return yield* new PeerLinkError({ + reason: "unreachable", + message: + refusals.length === checked.length + ? `This environment could not reach ${name}: ${refusals.join(" ")}` + : `This environment could not reach ${name} at ${urls.join(", ")}.`, + }); + } + // Each address is kept once, even when two spellings share an origin. + const origins = [...new Set(matching.map((found) => found.origin))]; + return { primary: first.origin, peer: first.descriptor, origins }; + }); /** The peer at `url`, with every address checked for credentials first. */ - const answeringAt = (urls: ReadonlyArray) => - Effect.gen(function* () { - const origins = yield* Effect.forEach(urls, peerOrigin); - const primary = origins[0]!; - const descriptor = yield* describe(primary); - if (Option.isNone(descriptor)) { - return yield* new PeerLinkError({ - reason: "not_a_t3_environment", - message: `Nothing at ${primary} answered as a T3 Code environment.`, - }); - } - return { primary, peer: descriptor.value, origins }; - }); + const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray) { + const origins = yield* Effect.forEach(urls, peerOrigin); + const primary = origins[0]!; + const descriptor = yield* describe(primary); + if (Option.isNone(descriptor)) { + return yield* new PeerLinkError({ + reason: "not_a_t3_environment", + message: `Nothing at ${primary} answered as a T3 Code environment.`, + }); + } + return { primary, peer: descriptor.value, origins }; + }); - const link: PeerLinks["Service"]["link"] = (input) => - Effect.gen(function* () { - const urls = [input.url, ...(input.alternateUrls ?? [])]; - // The user picked a machine: link through the addresses that prove to - // be it, so a reused LAN address never receives the pairing code. - const { primary, peer, origins } = - input.expectedEnvironmentId === undefined - ? yield* answeringAt(urls) - : yield* answeringAs( - urls, - input.expectedEnvironmentId, - input.expectedLabel ?? input.expectedEnvironmentId, - ); - const self = yield* environment.getDescriptor; - if (peer.environmentId === self.environmentId) { - return yield* new PeerLinkError({ - reason: "self", - message: "That address is this environment.", - }); - } - if (!linkLimitsHold(peer)) { - return yield* new PeerLinkError({ - reason: "incompatible", - message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, - }); - } - const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`); - const now = yield* DateTime.now; - const linked: PeerLink = { - environmentId: peer.environmentId, - label: peer.label, - urls: origins, - access: input.access, - linkedAt: now, - expiresAt: DateTime.add(now, { seconds: issued.expires_in }), - lastReachedAt: now, - lastError: null, - }; - // The token goes under a name of its own before the row points at it, - // so the row and its token are replaced together. - const secretName = yield* newSecretName; - yield* secrets - .set(secretName, new TextEncoder().encode(issued.access_token)) - .pipe(Effect.catch(failStorage)); - const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage)); - const previous = yield* readRow(peer.environmentId); - yield* sql` + const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) { + const urls = [input.url, ...(input.alternateUrls ?? [])]; + // The user picked a machine: link through the addresses that prove to + // be it, so a reused LAN address never receives the pairing code. + const { primary, peer, origins } = + input.expectedEnvironmentId === undefined + ? yield* answeringAt(urls) + : yield* answeringAs( + urls, + input.expectedEnvironmentId, + input.expectedLabel ?? input.expectedEnvironmentId, + ); + const self = yield* environment.getDescriptor; + if (peer.environmentId === self.environmentId) { + return yield* new PeerLinkError({ + reason: "self", + message: "That address is this environment.", + }); + } + if (!linkLimitsHold(peer)) { + return yield* new PeerLinkError({ + reason: "incompatible", + message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, + }); + } + const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`); + const now = yield* DateTime.now; + const linked: PeerLink = { + environmentId: peer.environmentId, + label: peer.label, + urls: origins, + access: input.access, + linkedAt: now, + expiresAt: DateTime.add(now, { seconds: issued.expires_in }), + lastReachedAt: now, + lastError: null, + }; + // The token goes under a name of its own before the row points at it, + // so the row and its token are replaced together. + const secretName = yield* newSecretName; + yield* secrets + .set(secretName, new TextEncoder().encode(issued.access_token)) + .pipe(Effect.catch(failStorage)); + const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage)); + const previous = yield* readRow(peer.environmentId); + yield* sql` INSERT INTO peer_environment_links ( environment_id, secret_name, label, urls_json, access, linked_at, expires_at, last_reached_at, last_error, fenced @@ -448,13 +450,13 @@ const make = Effect.gen(function* () { last_reached_at = excluded.last_reached_at, last_error = NULL `.pipe(Effect.catch(failStorage)); - // Linking again replaces the old token. A racing link may leave its own - // behind; it is unused either way. - if (Option.isSome(previous) && previous.value.secret_name !== secretName) { - yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore); - } - return linked; - }); + // Linking again replaces the old token. A racing link may leave its own + // behind; it is unused either way. + if (Option.isSome(previous) && previous.value.secret_name !== secretName) { + yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore); + } + return linked; + }); const describeUrl: PeerLinks["Service"]["describe"] = (url) => peerOrigin(url).pipe( @@ -498,8 +500,8 @@ const make = Effect.gen(function* () { ), ); - const unlink: PeerLinks["Service"]["unlink"] = (environmentId) => - Effect.gen(function* () { + const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")( + function* (environmentId) { const deleted = yield* sql<{ secret_name: string }>` DELETE FROM peer_environment_links WHERE environment_id = ${environmentId} RETURNING secret_name @@ -508,10 +510,11 @@ const make = Effect.gen(function* () { yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage)); } return deleted.length > 0; - }); + }, + ); - const resolve: PeerLinks["Service"]["resolve"] = (environmentId) => - Effect.gen(function* () { + const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")( + function* (environmentId) { const row = yield* readRow(environmentId); if (Option.isNone(row)) { return yield* new PeerLinkError({ @@ -568,7 +571,8 @@ const make = Effect.gen(function* () { }); } return { link, url: url.value, token: new TextDecoder().decode(stored.value) }; - }); + }, + ); const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) => DateTime.now.pipe( diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx index a7e5dde46658..9fb63229623e 100644 --- a/apps/web/src/components/chat/LinkRequestCard.tsx +++ b/apps/web/src/components/chat/LinkRequestCard.tsx @@ -277,7 +277,7 @@ function LinkRequestDialog(props: { } let code = pairingCode; if (canMint && targetId !== null) { - const minted = await mintPairingCodeOn(targetId); + const minted = await mintPairingCodeOn(targetId, access); if (Result.isFailure(minted)) { setMintFailed((failed) => new Set(failed).add(targetId)); setError(linkRequestFailureMessage(minted.failure)); diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 97475a684860..93fdc6fcb614 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -207,7 +207,7 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi // Settles to the code to link with, or null after reporting why there is none. const resolvePairingCode = async () => { if (!canMint || targetId === null) return pairingCode.trim(); - const minted = await mintPairingCodeOn(targetId); + const minted = await mintPairingCodeOn(targetId, access); if (Result.isSuccess(minted)) return minted.success; setMintFailed((failed) => new Set(failed).add(targetId)); failureToast("Could not link the environment", linkRequestFailureMessage(minted.failure)); diff --git a/apps/web/src/state/peerPairingCode.ts b/apps/web/src/state/peerPairingCode.ts index e90cd7efe6a3..3ac16819ecc9 100644 --- a/apps/web/src/state/peerPairingCode.ts +++ b/apps/web/src/state/peerPairingCode.ts @@ -1,6 +1,6 @@ import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts"; import * as Result from "effect/Result"; import { connectionAtomRuntime } from "../connection/runtime"; @@ -10,13 +10,14 @@ const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime); /** * A fresh pairing code minted on `environmentId` with this client's session - * there, for answering a link request. Fails with `PeerPairingCodeError` when - * the session may not create one. + * there, for linking with `access`. Fails with `PeerPairingCodeError` when the + * session may not create one. */ export async function mintPairingCodeOn( environmentId: EnvironmentId, + access: AuthMcpClientAccess, ): Promise> { - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: undefined }); + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access }); return result._tag === "Success" ? Result.succeed(result.value) : Result.fail(squashAtomCommandFailure(result)); diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts index a9d5ee9cabdb..0a60ec08ce73 100644 --- a/packages/client-runtime/src/state/peerPairingCode.ts +++ b/packages/client-runtime/src/state/peerPairingCode.ts @@ -1,14 +1,11 @@ /** * A pairing code for linking, minted on the environment being linked to with * the user's own session there, so a link card can be answered without the - * user fetching a code by hand. The code is one-use, carries only what an - * agent sign-in needs, and goes straight into the link answer. + * user fetching a code by hand. The code is one-use, carries exactly what an + * agent sign-in with the chosen access needs, and goes straight into the link + * answer. */ -import { - type AuthGrantScope, - AuthOrchestrationOperateScope, - AuthOrchestrationReadScope, -} from "@t3tools/contracts"; +import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import type * as HttpClient from "effect/http/HttpClient"; @@ -26,11 +23,6 @@ import { createEnvironmentCommand } from "./runtime.ts"; const MINT_TIMEOUT_MS = 8_000; const PEER_PAIRING_CODE_LABEL = "T3 Code link"; -/** An agent signing in there needs these, whatever access the user picks. */ -const LINK_SCOPES: ReadonlyArray = [ - AuthOrchestrationReadScope, - AuthOrchestrationOperateScope, -]; /** Minting failed; the user can still paste a code from the other environment. */ export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{ @@ -46,6 +38,7 @@ export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* ( prepared: PreparedConnection, + access: AuthMcpClientAccess, ): Effect.fn.Return { const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner); const remoteAuthorization = yield* Effect.serviceOption( @@ -62,7 +55,7 @@ const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode") request: ({ client, headers }) => client.pairingCredential({ headers, - payload: { label: PEER_PAIRING_CODE_LABEL, scopes: LINK_SCOPES }, + payload: { label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) }, }), }).pipe( Effect.mapError( @@ -89,17 +82,16 @@ export function createPeerPairingCodeCommand( ) { return createEnvironmentCommand(runtime, { label: "environment-data:peer-pairing-code:mint", - execute: (_input: void) => - Effect.gen(function* () { - const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const prepared = yield* SubscriptionRef.get(supervisor.prepared); - if (Option.isNone(prepared)) { - return yield* new PeerPairingCodeError({ - reason: "unavailable", - cause: "The environment is not connected.", - }); - } - return yield* mintPeerPairingCode(prepared.value); - }), + execute: Effect.fn(function* (access: AuthMcpClientAccess) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const prepared = yield* SubscriptionRef.get(supervisor.prepared); + if (Option.isNone(prepared)) { + return yield* new PeerPairingCodeError({ + reason: "unavailable", + cause: "The environment is not connected.", + }); + } + return yield* mintPeerPairingCode(prepared.value, access); + }), }); } diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 0ce47dbb9f8a..844e714f111c 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -400,6 +400,19 @@ export const AuthMcpClientAccess = Schema.Literals([ ]); export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type; +/** The scopes an agent session gets for an access level, and a pairing code must carry. */ +export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray => + access === "read-only" + ? [AuthOrchestrationReadScope] + : access === "full-access" + ? [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + AuthSourceControlWriteScope, + ] + : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; + export const AuthMcpProtectedResourceMetadata = Schema.Struct({ resource: Schema.String, authorization_servers: Schema.Array(Schema.String), From a0c623abd846b5bfc99a23234dda490b7b949862 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:40:54 -0700 Subject: [PATCH 138/408] feat(web,mobile): @-mention a machine as a context chip Typing @ and part of a machine's name in the composer now offers the user's other T3 Code environments beside threads and files, each with its machine icon. Picking one inserts a chip. The message carries only the machine's identity (environmentId and label, never an address), and the agent is told to link it with t3_environment_link if it is not linked yet, then pass the environmentId to delegate_task, t3_thread_launch and the other tools. Web keeps mentioned machines in the draft beside attached threads, persists them, restores them on undo and failed sends, and renders the chip in the composer and in sent messages. Mobile offers them in the @ popover and draws the chip natively. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../assets/context-chip-icons/server.png | Bin 0 -> 506 bytes .../scripts/sync-context-chip-icons.mjs | 1 + .../src/components/ComposerContextSheet.tsx | 3 + .../threads/ComposerCommandPopover.tsx | 13 +++ .../features/threads/NewTaskDraftScreen.tsx | 2 + .../src/features/threads/ThreadComposer.tsx | 2 + .../threads/use-composer-command-menu.ts | 45 +++++++- .../src/lib/composerChipPresentation.test.ts | 11 ++ .../src/lib/composerChipPresentation.ts | 2 + apps/mobile/src/lib/composerContext.ts | 16 +++ .../src/lib/contextChipIcons.generated.ts | 1 + apps/mobile/src/state/environments.ts | 17 ++- .../web/src/components/ChatView.logic.test.ts | 1 + apps/web/src/components/ChatView.logic.ts | 6 + apps/web/src/components/ContextChip.tsx | 2 + .../src/components/EnvironmentContextChip.tsx | 40 +++++++ apps/web/src/components/chat/ChatComposer.tsx | 59 ++++++++++ .../components/chat/ComposerCommandMenu.tsx | 18 +++ .../chat/UserMessageContextChips.tsx | 11 ++ apps/web/src/components/chat/chatViewSend.ts | 1 + .../components/chat/composerContextUndo.ts | 8 +- .../chat/useComposerContextImport.ts | 15 ++- .../components/chat/useComposerMenuItems.ts | 24 +++- .../src/components/chat/useComposerSend.ts | 22 +++- .../src/components/chat/useQueuedRunEdit.ts | 3 + .../composerContextPresentation.tsx | 34 +++++- .../components/contextPresentationRegistry.ts | 4 + apps/web/src/composerDraftStore.test.ts | 64 ++++++++++- apps/web/src/composerDraftStore.ts | 106 +++++++++++++++++- apps/web/src/lib/composerContextRecords.ts | 23 ++++ .../src/composerThreadItems.test.ts | 45 ++++++++ .../client-runtime/src/composerThreadItems.ts | 50 ++++++++- .../contracts/src/composerContext.test.ts | 6 + packages/contracts/src/composerContext.ts | 14 +++ .../src/composerContextReferences.test.ts | 21 ++++ .../shared/src/composerContextReferences.ts | 6 + 36 files changed, 680 insertions(+), 16 deletions(-) create mode 100644 apps/mobile/assets/context-chip-icons/server.png create mode 100644 apps/mobile/src/lib/composerChipPresentation.test.ts create mode 100644 apps/web/src/components/EnvironmentContextChip.tsx create mode 100644 packages/client-runtime/src/composerThreadItems.test.ts diff --git a/apps/mobile/assets/context-chip-icons/server.png b/apps/mobile/assets/context-chip-icons/server.png new file mode 100644 index 0000000000000000000000000000000000000000..92bc2ce457f16e0f12f68b26b08079186954b21f GIT binary patch literal 506 zcmV;6@c2mMuLR z-9u5?JY*#jQm~U$6;kc|CuKL0JU`=cY=1K$8UY5t6_5k>kvwj!8F0Ky;%C4TSQ9Uw zzydhkHu)#un{?O!Mc3q?Ntb33fMH@^-d733CIObD&s$TsUwdA72X24^iv%}TU;?ZH zjd9?6DGMleZIM!m;A89y&I7@R7Ae3{AgA0HJoQCd=@JH~ll=1*Eb>?kHVjI%M<#y6mJ_YIW*mVvSiB*Ej<)KsZ zwdt@3G{#tPW1qK{eG{%@0++zu9$a~KecV{bJ6(+lA%sKz0OSuy0r>+e~^RH^=dqLjV8(07*qoM6N<$g2Z*xD*ylh literal 0 HcmV?d00001 diff --git a/apps/mobile/scripts/sync-context-chip-icons.mjs b/apps/mobile/scripts/sync-context-chip-icons.mjs index aac4983d75e2..d99d4d3c9847 100644 --- a/apps/mobile/scripts/sync-context-chip-icons.mjs +++ b/apps/mobile/scripts/sync-context-chip-icons.mjs @@ -43,6 +43,7 @@ const lucideIcons = [ "message-circle", "messages-square", "mouse-pointer-click", + "server", "terminal", ]; diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsx index 1cafc5814c54..a33b5563f697 100644 --- a/apps/mobile/src/components/ComposerContextSheet.tsx +++ b/apps/mobile/src/components/ComposerContextSheet.tsx @@ -314,6 +314,9 @@ export function ComposerContextSheet(props: { ) : null} ) : null} + {record.kind === "environment" ? ( + + ) : null} {record.kind === "skill" ? ( diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx index cd924e4c61f0..cbe89f5fb876 100644 --- a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx +++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx @@ -3,6 +3,8 @@ import { type ProviderSkillSourceKind, } from "@t3tools/client-runtime/providerSkills"; import type { + EnvironmentId, + EnvironmentMachineKind, PullRequestContextMetadata, ScopedThreadRef, ServerProviderSkill, @@ -14,6 +16,7 @@ import { Pressable, ScrollView, StyleSheet, View, type ViewStyle } from "react-n import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; +import { ENVIRONMENT_MACHINE_SYMBOLS } from "../../components/EnvironmentMachineSymbol"; import { GlassSurface } from "../../components/ui/GlassSurface"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; import { pullRequestStatus } from "../pull-requests/pullRequestStatus"; @@ -40,6 +43,14 @@ export type ComposerCommandItem = readonly label: string; readonly description: string; } + | { + readonly id: string; + readonly type: "environment"; + readonly environmentId: EnvironmentId; + readonly machine: EnvironmentMachineKind; + readonly label: string; + readonly description: string; + } | { readonly id: string; readonly type: "slash-command"; @@ -110,6 +121,8 @@ function itemIcon(item: ComposerCommandItem): AppSymbolName | null { return null; case "thread": return "text.bubble"; + case "environment": + return ENVIRONMENT_MACHINE_SYMBOLS[item.machine]; } } diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 453b6829bd62..b27a3f163202 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -113,6 +113,7 @@ import { waitForComposerDraftsLoaded, } from "../../state/use-composer-drafts"; import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities"; +import { useMentionableEnvironments } from "../../state/environments"; import { useProjectClone } from "../../state/projectClones"; import { projectEnvironment } from "../../state/projects"; import { sourceControlEnvironment } from "../../state/sourceControl"; @@ -483,6 +484,7 @@ export function NewTaskDraftScreen(props: { ownerKey: flow.draftKey, environmentId: selectedProject?.environmentId ?? null, threadShells: useThreadShells(), + environments: useMentionableEnvironments(), pullRequestProjectId: selectedEnvironmentServerConfig?.environment.capabilities.pullRequests ? (selectedProject?.id ?? null) : null, diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index a55498552b4f..af7dad56157d 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -62,6 +62,7 @@ import { import { appAtomRegistry } from "../../state/atom-registry"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useThreadShells } from "../../state/entities"; +import { useMentionableEnvironments } from "../../state/environments"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { AppText as Text } from "../../components/ui/AppText"; @@ -472,6 +473,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ownerKey: composerDraftKey, environmentId: props.environmentId, threadShells: useThreadShells(), + environments: useMentionableEnvironments(), currentThreadId: props.selectedThread.id, projectCwd: props.projectCwd, pullRequestProjectId: props.serverConfig?.environment.capabilities.pullRequests diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts index 67e560b8eaa3..65e128178f8b 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.ts +++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts @@ -7,16 +7,25 @@ import type { ThreadId, ThreadPullRequestLink, } from "@t3tools/contracts"; -import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems"; +import { + type ComposerEnvironmentCandidate, + matchComposerEnvironmentItems, + matchComposerThreadItems, +} from "@t3tools/client-runtime/composerThreadItems"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; const EMPTY_THREAD_SHELLS: ReadonlyArray = []; +const EMPTY_ENVIRONMENTS: ReadonlyArray = []; import { COMPOSER_CONTEXT_MAX_RECORDS, PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS, } from "@t3tools/contracts"; import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; -import { pullRequestComposerContext, threadComposerContext } from "../../lib/composerContext"; +import { + environmentComposerContext, + pullRequestComposerContext, + threadComposerContext, +} from "../../lib/composerContext"; import { uuidv4 } from "../../lib/uuid"; import { getComposerDraftSnapshot, @@ -172,6 +181,7 @@ export function useComposerCommandMenu({ ownerKey, environmentId, threadShells = EMPTY_THREAD_SHELLS, + environments = EMPTY_ENVIRONMENTS, currentThreadId = null, projectCwd, pullRequestProjectId = null, @@ -190,6 +200,7 @@ export function useComposerCommandMenu({ readonly ownerKey: string | null; readonly environmentId: EnvironmentId | null; readonly threadShells?: ReadonlyArray; + readonly environments?: ReadonlyArray; readonly currentThreadId?: ThreadId | null; readonly projectCwd: string | null; readonly pullRequestProjectId?: ProjectId | null; @@ -502,8 +513,12 @@ export function useComposerCommandMenu({ query: trigger.query, }) : []; + const environmentItems = environmentId + ? matchComposerEnvironmentItems({ environments, environmentId, query: trigger.query }) + : []; return [ ...threadItems, + ...environmentItems, ...pathSearch.entries.map((entry) => { const parts = entry.path.split("/"); return { @@ -523,6 +538,32 @@ export function useComposerCommandMenu({ const onSelect = (item: ComposerCommandItem) => { if (!trigger) return; + if (item.type === "environment") { + if (!ownerKey || trigger.kind !== "path") return; + const record = environmentComposerContext(item.environmentId, item.label); + const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? []; + const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId); + if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) { + Dialog.alert("Too many context items", "Remove some context from the draft and try again."); + return; + } + const result = replaceTextRange( + draftMessage, + trigger.rangeStart, + trigger.rangeEnd, + `${formatComposerContextReference(record)} `, + ); + onChangeDraftMessage(result.text); + if (!alreadyAttached) { + const draft = getComposerDraftSnapshot(ownerKey); + setComposerDraftContext(ownerKey, { + version: 1, + records: [...(draft.context?.records ?? []), record], + }); + } + setSelection({ start: result.cursor, end: result.cursor }); + return; + } if (item.type === "thread") { if (!ownerKey || trigger.kind !== "path") return; const shell = threadShells.find( diff --git a/apps/mobile/src/lib/composerChipPresentation.test.ts b/apps/mobile/src/lib/composerChipPresentation.test.ts new file mode 100644 index 000000000000..2af545362667 --- /dev/null +++ b/apps/mobile/src/lib/composerChipPresentation.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vite-plus/test"; + +describe("contextChipPresentation", () => { + it("draws a mentioned machine as a machine, not the generic file chip", async () => { + const { contextChipPresentation } = await import("./composerChipPresentation"); + expect(contextChipPresentation("environment")).toEqual({ + accent: "#3f9a4f", + icon: "server", + }); + }); +}); diff --git a/apps/mobile/src/lib/composerChipPresentation.ts b/apps/mobile/src/lib/composerChipPresentation.ts index 257234fd02b4..2cd36b6a6b13 100644 --- a/apps/mobile/src/lib/composerChipPresentation.ts +++ b/apps/mobile/src/lib/composerChipPresentation.ts @@ -37,6 +37,8 @@ const CONTEXT_CHIP_PRESENTATIONS = { accent: "#009c96", icon: "messages-square", }, + // A machine: the record carries only its identity, so every machine wears one glyph. + environment: { accent: "#3f9a4f", icon: "server" }, } as const satisfies Record; export const UNAVAILABLE_CONTEXT_CHIP_PRESENTATION: ContextChipPresentation = { diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 03e50acf3de5..bf1eff901d5f 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -13,6 +13,8 @@ import { type ScopedThreadRef, type ServerProviderSkill, type ThreadContextRecord, + type EnvironmentContextRecord, + type EnvironmentId, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { @@ -114,6 +116,20 @@ export function threadComposerContext(ref: ScopedThreadRef, title: string): Thre }; } +/** Same identity as web: one record per machine, so mentioning it again reuses the chip. */ +export function environmentComposerContext( + environmentId: EnvironmentId, + label: string, +): EnvironmentContextRecord { + return { + version: 1, + kind: "environment", + contextId: ComposerContextId.make(`environment_${environmentId}`), + label: sanitizeComposerContextLabel(label, "environment"), + environmentId, + }; +} + export function pullRequestComposerContext( pullRequest: PullRequestContextMetadata, id: string, diff --git a/apps/mobile/src/lib/contextChipIcons.generated.ts b/apps/mobile/src/lib/contextChipIcons.generated.ts index 10a8b6af70ad..809f76dca49c 100644 --- a/apps/mobile/src/lib/contextChipIcons.generated.ts +++ b/apps/mobile/src/lib/contextChipIcons.generated.ts @@ -11,6 +11,7 @@ export const CONTEXT_CHIP_ICON_SOURCES = { "message-circle": require("../../assets/context-chip-icons/message-circle.png"), "messages-square": require("../../assets/context-chip-icons/messages-square.png"), "mouse-pointer-click": require("../../assets/context-chip-icons/mouse-pointer-click.png"), + server: require("../../assets/context-chip-icons/server.png"), skill: require("../../assets/context-chip-icons/skill.png"), terminal: require("../../assets/context-chip-icons/terminal.png"), } as const satisfies Readonly>; diff --git a/apps/mobile/src/state/environments.ts b/apps/mobile/src/state/environments.ts index 776a615f46af..7bfd41e1ca88 100644 --- a/apps/mobile/src/state/environments.ts +++ b/apps/mobile/src/state/environments.ts @@ -4,7 +4,8 @@ import { hasRelayRoute, type EnvironmentPresentation as BaseEnvironmentPresentation, } from "@t3tools/client-runtime/connection"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { ComposerEnvironmentCandidate } from "@t3tools/client-runtime/composerThreadItems"; +import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts"; import { useMemo } from "react"; import { environmentCatalog } from "../connection/catalog"; @@ -55,3 +56,17 @@ export function useEnvironments() { export function useEnvironmentConnectionState(environmentId: EnvironmentId) { return useEnvironmentQuery(environmentCatalog.stateAtom(environmentId)); } + +/** The user's machines as `@` mention candidates, drawn with their machine kind. */ +export function useMentionableEnvironments(): ReadonlyArray { + const { environments } = useEnvironments(); + return useMemo( + () => + environments.map((environment) => ({ + environmentId: environment.environmentId, + label: environment.label, + machine: resolveEnvironmentMachineKind(environment.serverConfig), + })), + [environments], + ); +} diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index a03a7929b091..736d170d7f67 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1062,6 +1062,7 @@ describe("snapshotComposerSend", () => { previewAnnotations: [], reviewComments: [], threadContexts: [], + environmentContexts: [], }); expect(snapshot.terminalContexts).toEqual([live]); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 1928cd21b12c..4254d97cf308 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -39,6 +39,7 @@ import { type ScopedProjectRef, type ScopedThreadRef, type ThreadContextRecord, + type EnvironmentContextRecord, type ThreadId, type ThreadLinkedPullRequest, type RunId, @@ -1294,6 +1295,7 @@ export interface PlanFollowUpComposerSnapshot { readonly reviewComments: ReadonlyArray; readonly previewAnnotations: ReadonlyArray; readonly threadContexts: ReadonlyArray; + readonly environmentContexts: ReadonlyArray; } /** @@ -1308,6 +1310,7 @@ export function restorePlanFollowUpComposer(input: { readonly writeReviewComments: (comments: ReadonlyArray) => void; readonly writePreviewAnnotations: (annotations: ReadonlyArray) => void; readonly writeThreadContexts: (records: ReadonlyArray) => void; + readonly writeEnvironmentContexts: (records: ReadonlyArray) => void; readonly resetCursor: (options: { cursor: number; prompt: string; @@ -1319,6 +1322,7 @@ export function restorePlanFollowUpComposer(input: { input.writeReviewComments(input.snapshot.reviewComments); input.writePreviewAnnotations(input.snapshot.previewAnnotations); input.writeThreadContexts(input.snapshot.threadContexts); + input.writeEnvironmentContexts(input.snapshot.environmentContexts); input.resetCursor({ cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length), prompt: input.snapshot.prompt, @@ -1484,6 +1488,7 @@ export interface ComposerSendContents { readonly previewAnnotations: ReadonlyArray; readonly reviewComments: ReadonlyArray; readonly threadContexts: ReadonlyArray; + readonly environmentContexts: ReadonlyArray; } /** @@ -1503,6 +1508,7 @@ export function snapshotComposerSend(contents: ComposerSendContents) { previewAnnotations: [...contents.previewAnnotations], reviewComments: [...contents.reviewComments], threadContexts: [...contents.threadContexts], + environmentContexts: [...contents.environmentContexts], messageText: contents.terminalContexts .filter((context) => !terminalContexts.includes(context)) .reduce( diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsx index 72633d478e11..ec1481079076 100644 --- a/apps/web/src/components/ContextChip.tsx +++ b/apps/web/src/components/ContextChip.tsx @@ -27,6 +27,7 @@ const contextChipVariants = cva( "pr-closed": "[--context-chip-accent:oklch(0.62_0.16_16)]", skill: "[--context-chip-accent:oklch(0.62_0.16_322)]", thread: "[--context-chip-accent:oklch(0.62_0.12_190)]", + environment: "[--context-chip-accent:oklch(0.62_0.11_145)]", citation: "[--context-chip-accent:oklch(0.62_0.16_259)]", }, state: { @@ -52,6 +53,7 @@ const contextChipVariants = cva( "pr-closed", "skill", "thread", + "environment", "citation", ], className: diff --git a/apps/web/src/components/EnvironmentContextChip.tsx b/apps/web/src/components/EnvironmentContextChip.tsx new file mode 100644 index 000000000000..9730fc7c342c --- /dev/null +++ b/apps/web/src/components/EnvironmentContextChip.tsx @@ -0,0 +1,40 @@ +import { type EnvironmentContextRecord, resolveEnvironmentMachineKind } from "@t3tools/contracts"; + +import { useEnvironment } from "~/state/environments"; +import { ContextChip, ContextChipLabel } from "./ContextChip"; +import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; + +/** + * Inline chip for a mentioned machine, in the composer and in sent messages. Prefers the + * name this client knows the machine by, and draws it with its machine icon. + */ +export function EnvironmentContextChip(props: { + record: Pick; + copyMarkdown?: string; +}) { + const environment = useEnvironment(props.record.environmentId); + const label = environment?.label.trim() || props.record.label; + return ( + + + + {label} + + } + /> + + {environment ? "T3 Code environment" : "Machine not in this app"} + + + ); +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b74e691ddd13..ac15a6285c96 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -22,6 +22,7 @@ import type { PreviewAnnotationPayload, ProviderApprovalDecision, ThreadContextRecord, + EnvironmentContextRecord, ProviderInteractionMode, ResolvedKeybindingsConfig, RuntimeMode, @@ -182,6 +183,8 @@ import { terminalContextRecord, threadContextRecord, threadContextReference, + environmentContextRecord, + environmentContextReference, } from "~/lib/composerContextRecords"; import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; @@ -347,6 +350,7 @@ export interface ChatComposerHandle { previewAnnotations: PreviewAnnotationPayload[]; reviewComments: ReviewCommentContext[]; threadContexts: ThreadContextRecord[]; + environmentContexts: EnvironmentContextRecord[]; selectedPromptEffort: string | null; selectedModelOptionsForDispatch: unknown; selectedModelSelection: ModelSelection; @@ -739,6 +743,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerPreviewAnnotations = composerDraft.previewAnnotations; const composerReviewComments = composerDraft.reviewComments; const composerThreadContexts = attachmentDraft.threadContexts; + const composerEnvironmentContexts = composerDraft.environmentContexts; const { pendingSnapShotAnimations, pendingSnapShotIds, @@ -789,6 +794,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) reviewComments: composerReviewComments, previewAnnotations: composerPreviewAnnotations, threadContexts: composerThreadContexts, + environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, uploadsByImageId, @@ -1209,6 +1215,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedProviderSkills, selectedProviderSlashCommands, showSkillsInSlashMenu: settings.showSkillsInSlashMenu, + questionAttachmentTarget, }); const composerMenuOpen = Boolean(composerTrigger); @@ -1361,6 +1368,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts); const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts); + const addComposerDraftEnvironmentContexts = useComposerDraftStore( + (store) => store.addEnvironmentContexts, + ); + const setComposerDraftEnvironmentContexts = useComposerDraftStore( + (store) => store.setEnvironmentContexts, + ); const buildContextClipboardFragment = (contextIds: ReadonlyArray): string | null => { const wanted = new Set(contextIds); const copiedFiles = new Map(); @@ -1377,6 +1390,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) .filter((c) => wanted.has(terminalContextReference(c).contextId)) .map(terminalContextRecord), ...composerThreadContexts.filter((record) => wanted.has(record.contextId)), + ...composerEnvironmentContexts.filter((record) => wanted.has(record.contextId)), ...composerReviewComments .filter((c) => wanted.has(reviewCommentContextId(c.id))) .map(reviewCommentContextRecord), @@ -1756,6 +1770,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerDraftThreadContexts(composerDraftTarget, nextThreads); } + const liveEnvironmentIds = new Set( + composerEnvironmentContexts.map((record) => record.contextId), + ); + const restoredEnvironments = [...referenced].flatMap((contextId) => { + if (liveEnvironmentIds.has(contextId)) return []; + const record = retained.environments.get(contextId); + return record ? [record] : []; + }); + const nextEnvironments = [ + ...composerEnvironmentContexts.filter((record) => referenced.has(record.contextId)), + ...restoredEnvironments, + ]; + for (const record of composerEnvironmentContexts) { + if (!referenced.has(record.contextId)) retained.environments.set(record.contextId, record); + } + if ( + nextEnvironments.length !== composerEnvironmentContexts.length || + restoredEnvironments.length > 0 + ) { + setComposerDraftEnvironmentContexts(composerDraftTarget, nextEnvironments); + } + for (const comment of composerReviewComments) { const contextId = reviewCommentContextId(comment.id); if (!referenced.has(contextId)) { @@ -2054,6 +2090,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } return; } + if (item.type === "environment") { + if (trigger.kind !== "path") return; + const record = environmentContextRecord(item.environmentId, item.label); + const replacement = `${formatInlineContextReference(environmentContextReference(record))} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + addComposerDraftEnvironmentContexts(composerDraftTarget, [record], { + appendReference: false, + }); + setComposerHighlightedItemId(null); + } + return; + } }; const onSelectComposerItemStable = useStableCallback(onSelectComposerItem); @@ -3269,6 +3325,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) previewAnnotations: composerPreviewAnnotations, reviewComments: composerReviewComments, threadContexts: composerThreadContexts, + environmentContexts: composerEnvironmentContexts, selectedPromptEffort, selectedModelOptionsForDispatch, selectedModelSelection, @@ -3324,6 +3381,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerTerminalContextsRef, composerPreviewAnnotations, composerReviewComments, + composerThreadContexts, + composerEnvironmentContexts, focusComposer, environmentId, primaryEnvironmentId, diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 4d556d48be70..d2f224b3f5be 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -5,6 +5,8 @@ import { type ProviderSkillSourceKind, } from "@t3tools/client-runtime/providerSkills"; import { + type EnvironmentId, + type EnvironmentMachineKind, type ProjectEntry, type ProviderDriverKind, type PullRequestContextMetadata, @@ -27,6 +29,7 @@ import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../compo import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command"; +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { ComposerBanner } from "./ComposerBanner"; import { resolvePullRequestState } from "../pullRequest/pullRequestPresentation"; @@ -77,6 +80,14 @@ export type ComposerCommandItem = thread: ScopedThreadRef; label: string; description: string; + } + | { + id: string; + type: "environment"; + environmentId: EnvironmentId; + machine: EnvironmentMachineKind; + label: string; + description: string; }; export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { @@ -202,6 +213,13 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { {props.item.type === "thread" ? (