diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 69c1ea6575a4a..315ff5742fd5c 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -22,6 +22,7 @@ github:btsouth github:cestercian github:chrisdeeming github:chuks-qua +-github:coygeek Filed over 270 automated issues, about 50 a day at peak, far past what maintainers can triage github:cursoragent github:D3OXY github:dbalders diff --git a/.github/workflows/agent-context-budget.yml b/.github/workflows/agent-context-budget.yml index 09f1dd2a87b63..37563d061562f 100644 --- a/.github/workflows/agent-context-budget.yml +++ b/.github/workflows/agent-context-budget.yml @@ -10,10 +10,7 @@ on: permissions: contents: read -concurrency: - group: agent-context-budget-${{ github.event.pull_request.number }} - cancel-in-progress: true - +# No concurrency group: label events arrive in bursts, and a cancelled run reports as a failed check. jobs: budget: name: Agent context budget diff --git a/.github/workflows/issue-vouch.yml b/.github/workflows/issue-vouch.yml new file mode 100644 index 0000000000000..bbb6e95c9ec60 --- /dev/null +++ b/.github/workflows/issue-vouch.yml @@ -0,0 +1,77 @@ +name: Issue Vouch + +on: + issues: + types: [opened, reopened] + push: + branches: + - main + paths: + - .github/VOUCHED.td + - .github/workflows/issue-vouch.yml + workflow_dispatch: + +permissions: + contents: read + issues: write + +concurrency: + group: issue-vouch-${{ github.event.issue.number || 'all' }} + cancel-in-progress: true + +jobs: + label: + name: Label issues by author trust + runs-on: ubuntu-24.04 + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { owner, repo } = context.repo; + // Only listed authors get a label; open issues number in the thousands, + // so unvouched is the default and stays unlabelled. + const labelByStatus = { vouched: "vouch:trusted", denounced: "vouch:denounced" }; + const managedLabelNames = new Set(["vouch:trusted", "vouch:unvouched", "vouch:denounced"]); + + const { data: file } = await github.rest.repos.getContent({ + owner, + repo, + path: ".github/VOUCHED.td", + ref: context.payload.repository.default_branch, + }); + const statusByUser = new Map(); + for (const raw of Buffer.from(file.content, "base64").toString("utf8").split("\n")) { + const match = /^(-?)github:(\S+)/.exec(raw.trim()); + if (match) statusByUser.set(match[2].toLowerCase(), match[1] ? "denounced" : "vouched"); + } + + const issues = + context.eventName === "issues" + ? [context.payload.issue] + : ( + await github.paginate(github.rest.issues.listForRepo, { + owner, + repo, + state: "open", + per_page: 100, + }) + ).filter((issue) => !issue.pull_request); + + for (const issue of issues) { + const status = statusByUser.get(issue.user.login.toLowerCase()); + const next = labelByStatus[status]; + const current = issue.labels.map((label) => label.name).filter((name) => managedLabelNames.has(name)); + + for (const name of current) { + if (name === next) continue; + try { + await github.rest.issues.removeLabel({ owner, repo, issue_number: issue.number, name }); + } catch (error) { + if (error.status !== 404) throw error; + } + } + if (next && !current.includes(next)) { + await github.rest.issues.addLabels({ owner, repo, issue_number: issue.number, labels: [next] }); + core.info(`Issue #${issue.number} (${issue.user.login}): ${status} -> ${next}`); + } + } diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index 39d368f9a20d6..eb53c07894025 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -101,17 +101,17 @@ jobs: { name: "vouch:trusted", color: "1f883d", - description: "PR author is trusted by repo permissions or the VOUCHED list.", + description: "Author is trusted by repo permissions or the VOUCHED list.", }, { name: "vouch:unvouched", color: "fbca04", - description: "PR author is not yet trusted in the VOUCHED list.", + description: "Author is not yet trusted in the VOUCHED list.", }, { name: "vouch:denounced", color: "d1242f", - description: "PR author is explicitly blocked by the VOUCHED list.", + description: "Author is explicitly blocked by the VOUCHED list.", }, ]; diff --git a/AGENTS.md b/AGENTS.md index ce90b3eefa3f8..e5941a175264c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # T3 Code -T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity, Kiro) and serves web, desktop, and mobile clients. +T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provider CLIs and agents (Codex, Claude Code, Cursor, Grok, OpenCode, Antigravity, Kiro, Pi, Muse Code, fx) and serves web, desktop, and mobile clients. You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor. @@ -68,7 +68,7 @@ The most common defect in this repo is a change that works on the path you teste - **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature. - **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime` -- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, Antigravity, and Kiro each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". +- **Providers.** Codex, Claude, Cursor, Grok, OpenCode, Antigravity, Kiro, Pi, Muse Code, fx, and ACP Registry each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here". - **Agents.** A capability a user can trigger is usually one an agent should reach through MCP tools, and scheduled tasks run the same paths. That only works when it is a service method, not handler code. - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts index 8a823cde8db79..de687d41a4e68 100644 --- a/apps/desktop/src/app/DesktopClerk.test.ts +++ b/apps/desktop/src/app/DesktopClerk.test.ts @@ -424,7 +424,7 @@ it.effect.each(["startup", "open-url", "early-second-instance"] as const)( ), Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks), ); - }).pipe(Effect.scoped), + }), ); it.effect("hands web and app links to the renderer and leaves other links alone", () => @@ -481,5 +481,5 @@ it.effect("hands web and app links to the renderer and leaves other links alone" }), ), ); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts index 2dc59c58899ee..dd61b7984ec1f 100644 --- a/apps/desktop/src/app/DesktopCliCommand.test.ts +++ b/apps/desktop/src/app/DesktopCliCommand.test.ts @@ -160,7 +160,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(yield* fs.exists(upgradedLink)).toBe(false); expect((yield* upgraded.install).installedPath).toBe(upgradedLink); } - }).pipe(Effect.scoped), + }), ); it.effect("never replaces or removes a t3 it did not create", () => @@ -202,7 +202,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect((yield* Effect.flip(command.install)).message).toContain("Could not set up"); yield* command.uninstall; expect(yield* fs.readFileString(launcher)).toBe("npm's t3\n"); - }).pipe(Effect.scoped), + }), ); it.effect("finds and removes a link left by a previous T3 home", () => @@ -259,7 +259,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { ); expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine"); - }).pipe(Effect.scoped), + }), ); it.effect("refuses to install behind another t3 that runs first", () => @@ -309,7 +309,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { installedPath: path.join(home, ".local", "bin", "t3"), }); expect(installed.shadowedBy).toBeUndefined(); - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( @@ -343,7 +343,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { onPath: true, installedPath: path.join(home, ".local", "bin", "t3"), }); - }).pipe(Effect.scoped), + }), ); it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () => @@ -372,7 +372,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(yield* command.state).toEqual(removed); expect(yield* fs.exists(installed.installedPath!)).toBe(false); expect(yield* fs.exists(launcher)).toBe(true); - }).pipe(Effect.scoped), + }), ); it.effect("leaves the Windows PATH alone when it cannot be read", () => @@ -411,7 +411,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner); yield* reader.install; expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 }); - }).pipe(Effect.scoped), + }), ); it.effect("does not claim or remove a Windows PATH entry the user added", () => @@ -441,6 +441,6 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner)) .installOnFirstLaunch; expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index e2f97c7d2ff71..3e8b4967dfde5 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -39,7 +39,7 @@ const run = (shim: string, args: ReadonlyArray, env: NodeJS.ProcessEnv = }); const REPORTER = - '#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME"\nprintf "%s\\n" "$@"\nexit 3\n'; + '#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME appimage=$APPIMAGE"\nprintf "%s\\n" "$@"\nexit 3\n'; const fakeAppImage = (canMount = true, app = REPORTER) => { const root = tempRoot(); @@ -56,7 +56,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { `echo $$ >'${root}/mounter.pid'`, canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open. - `trap 'echo unmounted >&3 2>/dev/null; touch "${root}/unmounted"; exit 0' TERM HUP INT`, + "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT", "trap 'echo mounted >&3 2>/dev/null' WINCH", "while :; do sleep 0.05; done", "", @@ -150,6 +150,14 @@ describe("renderCliShim", () => { ); }); + // The server skips its compile cache only under APPIMAGE; each mount path is new. + it("tells the CLI it runs from the mounted AppImage", () => { + const { appImage, shim } = fakeAppImage(); + const result = run(shim, ["--version"]); + expect(result.status).toBe(3); + expect(result.stdout).toContain(`appimage=${appImage}`); + }); + it("keeps the install's T3 home under sudo, unless one is set", () => { const root = tempRoot(); writeExecutable(NodePath.join(root, "app"), REPORTER); diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index eba61f561f526..217f3b327dc9e 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -109,6 +109,8 @@ export const renderCliShim = (input: { ' (cd "$work" && "$app" --appimage-extract >/dev/null) || { echo "Could not open $app." >&2; exit 1; }', ' mount="$work/squashfs-root"', "fi", + // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. + 'export APPIMAGE="$app"', run("$mount"), "", ].join("\n"); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index 98c75385afc51..5dfde9103f152 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -99,7 +99,7 @@ const withStore = ( prefix: "t3-desktop-connection-catalog-test-", }); return yield* effect.pipe(Effect.provide(layerFor(baseDir, encryptionAvailable))); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopConnectionCatalogStore", () => { it.effect("persists and reads an encrypted connection catalog", () => @@ -298,6 +298,6 @@ describe("DesktopConnectionCatalogStore", () => { assert.notEqual(error.message, decryptError.message); yield* Ref.set(failDecrypt, false); assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}')); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/app/DesktopExitChildren.test.ts b/apps/desktop/src/app/DesktopExitChildren.test.ts index 490c6740f0e00..800a0f5bd4c0f 100644 --- a/apps/desktop/src/app/DesktopExitChildren.test.ts +++ b/apps/desktop/src/app/DesktopExitChildren.test.ts @@ -3,7 +3,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import { assert, describe, it } from "@effect/vitest"; -import { stopChildProcessesBeforeExit } from "./DesktopExitChildren.ts"; +import { stopChildProcessesBeforeExit, stopZygotesBeforeExit } from "./DesktopExitChildren.ts"; const isRunning = (pid: number) => { try { @@ -39,4 +39,24 @@ describe.runIf(NodeFS.existsSync("/proc/self/task"))("stopChildProcessesBeforeEx parent.kill("SIGKILL"); } }); + + it("kills zygote children before returning and leaves other helpers running", async () => { + const spawnTitled = async (title: string) => { + const child = NodeChildProcess.spawn("sleep", ["60"], { argv0: title, stdio: "ignore" }); + await new Promise((resolve) => child.once("spawn", resolve)); + return child; + }; + // Chromium rewrites a zygote's argv into one space-separated title. + const zygote = await spawnTitled("/opt/T3 Code/t3code --type=zygote --no-sandbox"); + const utility = await spawnTitled("/opt/T3 Code/t3code --type=utility"); + try { + stopZygotesBeforeExit(process.pid); + + assert.isFalse(isRunning(zygote.pid!)); + assert.isTrue(isRunning(utility.pid!)); + } finally { + zygote.kill("SIGKILL"); + utility.kill("SIGKILL"); + } + }); }); diff --git a/apps/desktop/src/app/DesktopExitChildren.ts b/apps/desktop/src/app/DesktopExitChildren.ts index 7cc64c43833e7..9426c1b4ff884 100644 --- a/apps/desktop/src/app/DesktopExitChildren.ts +++ b/apps/desktop/src/app/DesktopExitChildren.ts @@ -29,6 +29,13 @@ const childPids = (pid: number): ReadonlyArray => { ); }; +// A zygote rewrites its argv into one space-separated title. +const isZygote = (pid: number): boolean => + (readProc(`/proc/${pid}/cmdline`) ?? "") + .replaceAll("\0", " ") + .split(" ") + .includes("--type=zygote"); + // A zombie has already released its memory mappings. const isRunning = (pid: number): boolean => { const stat = readProc(`/proc/${pid}/stat`); @@ -68,3 +75,13 @@ export const stopChildProcessesBeforeExit = (pid: number): ReadonlyArray waitUntilStopped(survivors, KILL_WAIT_MS); return survivors; }; + +/** + * Chromium's zygotes exit only after main does, so on an AppImage they outlive the mount even on + * an orderly quit. Kills them while main still holds the image mounted. Linux only (/proc). + */ +export const stopZygotesBeforeExit = (pid: number): void => { + const zygotes = childPids(pid).filter(isZygote); + signal(zygotes, "SIGKILL"); + waitUntilStopped(zygotes, KILL_WAIT_MS); +}; diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index d16b8e8a8b595..b7f99883f641c 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; @@ -117,6 +118,7 @@ describe("DesktopLifecycle", () => { const layerEnvironment = Layer.succeed(DesktopEnvironment.DesktopEnvironment, { platform, isDevelopment: false, + appImagePath: Option.none(), } as DesktopEnvironment.DesktopEnvironment["Service"]); const layer = DesktopLifecycle.layer.pipe( diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 75a5afefcdd34..3552976329b59 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -3,6 +3,7 @@ import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -13,7 +14,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts"; -import { stopChildProcessesBeforeExit } from "./DesktopExitChildren.ts"; +import { stopChildProcessesBeforeExit, stopZygotesBeforeExit } from "./DesktopExitChildren.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; import * as DesktopShutdown from "./DesktopShutdown.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; @@ -350,6 +351,13 @@ export const make = DesktopLifecycle.of({ quitFromSignal("SIGTERM", runEffect, quit); }); } + + // Unscoped: the app scope closes before Electron exits, and every exit path must run this. + if (environment.platform === "linux" && Option.isSome(environment.appImagePath)) { + yield* Effect.sync(() => { + process.once("exit", () => stopZygotesBeforeExit(process.pid)); + }); + } }).pipe(Effect.withSpan("desktop.lifecycle.register")), }); diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts index 7e685358865c7..e9c8336feaf4b 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -602,7 +602,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { } assert.isFalse(yield* fileSystem.exists(fixture.cachePath)); assert.equal(iconCacheRuns(run), 0); - }).pipe(Effect.scoped), + }), ); it.effect("replaces same-length stale icons and refreshes an existing cache once", () => @@ -634,7 +634,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { run.commands.filter(({ command }) => command === "gtk-update-icon-cache"), [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }], ); - }).pipe(Effect.scoped), + }), ); it.effect("refreshes when this launch changed an icon even if the cache looks newer", () => @@ -655,7 +655,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png"))); assert.equal(iconCacheRuns(run), 1); - }).pipe(Effect.scoped), + }), ); it.effect("retries a failed icon cache refresh on the next launch", () => @@ -678,7 +678,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { yield* registerWithRealFileSystem(recovering); yield* registerWithRealFileSystem(recovering); assert.equal(iconCacheRuns(recovering), 1); - }).pipe(Effect.scoped), + }), ); it.effect("still registers the handler when the theme icon install fails", () => @@ -702,6 +702,6 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { missingTool.commands.map(({ command }) => command), ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"], ); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index e96e036b0c88b..8a8389082ce89 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -199,129 +199,125 @@ function makeTestInstance(input: MakeInstanceInput) { describe("DesktopBackendManager", () => { it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () => - Effect.scoped( - Effect.gen(function* () { - const probe = yield* Deferred.make(); - const ready = yield* Deferred.make(); - const exit = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.acquireRelease( - Effect.succeed( - makeProcess({ - exitCode: Deferred.await(exit), - kill: () => - Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), - }), - ), - () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + Effect.gen(function* () { + const probe = yield* Deferred.make(); + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed( + makeProcess({ + exitCode: Deferred.await(exit), + kill: () => + Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), + }), ), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), ), ), - httpClientLayer: Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Deferred.succeed(probe, undefined).pipe( - Effect.andThen(Deferred.await(ready)), - Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))), - ), + ), + httpClientLayer: Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Deferred.succeed(probe, undefined).pipe( + Effect.andThen(Deferred.await(ready)), + Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))), ), ), - }); - yield* instance.start; - yield* Deferred.await(probe); - const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); - yield* Deferred.succeed(ready, undefined); - assert.isTrue(yield* Fiber.join(waiter)); - yield* instance.stop(); - assert.isFalse(yield* instance.waitForReady(Duration.seconds(15))); - }), - ), + ), + }); + yield* instance.start; + yield* Deferred.await(probe); + const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); + yield* Deferred.succeed(ready, undefined); + assert.isTrue(yield* Fiber.join(waiter)); + yield* instance.stop(); + assert.isFalse(yield* instance.waitForReady(Duration.seconds(15))); + }), ); it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () => - Effect.scoped( - Effect.gen(function* () { - let spawnedCommand: ChildProcess.Command | undefined; - let bootstrapJson = ""; - let telemetryJson = ""; - let readyCount = 0; - const ready = yield* Deferred.make(); - const exited = yield* Queue.unbounded(); - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => - Effect.gen(function* () { - spawnedCommand = command; - if (command._tag === "StandardCommand") { - const fd3 = command.options.additionalFds?.fd3; - if (fd3?.type === "input" && fd3.stream) { - bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString); - } - const fd4 = command.options.additionalFds?.fd4; - if (fd4?.type === "input" && fd4.stream) { - telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString); - } + Effect.gen(function* () { + let spawnedCommand: ChildProcess.Command | undefined; + let bootstrapJson = ""; + let telemetryJson = ""; + let readyCount = 0; + const ready = yield* Deferred.make(); + const exited = yield* Queue.unbounded(); + + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + spawnedCommand = command; + if (command._tag === "StandardCommand") { + const fd3 = command.options.additionalFds?.fd3; + if (fd3?.type === "input" && fd3.stream) { + bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString); } + const fd4 = command.options.additionalFds?.fd4; + if (fd4?.type === "input" && fd4.stream) { + telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString); + } + } - return makeProcess({ - exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - ), - ); + return makeProcess({ + exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }); + }), + ), + ); - const instance = yield* makeTestInstance({ - config: { - ...baseConfig, - bootstrap: configWithObservability, - }, - spawnerLayer: layerSpawner, - desktopTelemetryStream: Stream.encodeText( - Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'), - ), - onReady: Effect.sync(() => { - readyCount += 1; - }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid), - backendOutputLog: { - persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid), - }, - }); + const instance = yield* makeTestInstance({ + config: { + ...baseConfig, + bootstrap: configWithObservability, + }, + spawnerLayer: layerSpawner, + desktopTelemetryStream: Stream.encodeText( + Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'), + ), + onReady: Effect.sync(() => { + readyCount += 1; + }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid), + backendOutputLog: { + persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid), + }, + }); - yield* instance.start; - yield* Queue.take(exited); - - assert.equal(readyCount, 1); - assert.isDefined(spawnedCommand); - if (spawnedCommand._tag !== "StandardCommand") { - throw new Error("Expected backend to spawn a standard command."); - } - - assert.equal(spawnedCommand.command, "/electron"); - assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]); - assert.equal(spawnedCommand.options.cwd, "/server"); - assert.equal(spawnedCommand.options.extendEnv, true); - assert.equal(spawnedCommand.options.stdout, "pipe"); - assert.equal(spawnedCommand.options.stderr, "pipe"); - assert.equal(spawnedCommand.options.killSignal, "SIGTERM"); - assert.isDefined(spawnedCommand.options.forceKillAfter); - assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input"); - assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output"); - assert.equal( - Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)), - 5_000, - ); - - assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability); - assert.equal( - telemetryJson, - '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n', - ); - }), - ), + yield* instance.start; + yield* Queue.take(exited); + + assert.equal(readyCount, 1); + assert.isDefined(spawnedCommand); + if (spawnedCommand._tag !== "StandardCommand") { + throw new Error("Expected backend to spawn a standard command."); + } + + assert.equal(spawnedCommand.command, "/electron"); + assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]); + assert.equal(spawnedCommand.options.cwd, "/server"); + assert.equal(spawnedCommand.options.extendEnv, true); + assert.equal(spawnedCommand.options.stdout, "pipe"); + assert.equal(spawnedCommand.options.stderr, "pipe"); + assert.equal(spawnedCommand.options.killSignal, "SIGTERM"); + assert.isDefined(spawnedCommand.options.forceKillAfter); + assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input"); + assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output"); + assert.equal( + Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)), + 5_000, + ); + + assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability); + assert.equal( + telemetryJson, + '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n', + ); + }), ); it.effect("reports a SIGKILL exit without an exit code", () => @@ -349,285 +345,272 @@ describe("DesktopBackendManager", () => { ); it.effect("reports child exit before waiting for trailing output to drain", () => - Effect.scoped( - Effect.gen(function* () { - const exitObserved = yield* Deferred.make(); - const finishOutputDrain = yield* Deferred.make(); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - stdout: Stream.fromEffect( - Deferred.await(finishOutputDrain).pipe( - Effect.as(new TextEncoder().encode("trailing output\n")), - ), + Effect.gen(function* () { + const exitObserved = yield* Deferred.make(); + const finishOutputDrain = yield* Deferred.make(); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + stdout: Stream.fromEffect( + Deferred.await(finishOutputDrain).pipe( + Effect.as(new TextEncoder().encode("trailing output\n")), ), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), - }), - ), + ), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + }), ), - ); + ), + ); - const runFiber = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid), - }).pipe( - Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), - Effect.forkChild, - ); - - yield* Deferred.await(exitObserved); - assert.isUndefined(runFiber.pollUnsafe()); - - yield* Deferred.succeed(finishOutputDrain, void 0); - assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1); - }), - ), + const runFiber = yield* DesktopBackendManager.runBackendProcess({ + ...baseConfig, + desktopTelemetryStream: Stream.empty, + onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid), + }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), Effect.forkChild); + + yield* Deferred.await(exitObserved); + assert.isUndefined(runFiber.pollUnsafe()); + + yield* Deferred.succeed(finishOutputDrain, void 0); + assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1); + }), ); it.effect("continues routing desktop telemetry control messages after an invalid line", () => - Effect.scoped( - Effect.gen(function* () { - const handled = yield* Deferred.make(); - const controlMessage = encodeDesktopTelemetryControl({ - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - getOutputFd: (fd) => - fd === 5 - ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`)) - : Stream.empty, - exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }), - ), + Effect.gen(function* () { + const handled = yield* Deferred.make(); + const controlMessage = encodeDesktopTelemetryControl({ + version: 1, + type: "setDiagnosticsDemand", + enabled: true, + }); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + getOutputFd: (fd) => + fd === 5 + ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`)) + : Stream.empty, + exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }), ), - ); - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - desktopTelemetryPublisher: { - handleControlForSource: (_sourceId, message) => - message.type === "setDiagnosticsDemand" - ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid) - : Effect.void, - }, - }); + ), + ); + const instance = yield* makeTestInstance({ + spawnerLayer: layerSpawner, + desktopTelemetryPublisher: { + handleControlForSource: (_sourceId, message) => + message.type === "setDiagnosticsDemand" + ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid) + : Effect.void, + }, + }); - yield* instance.start; - assert.isTrue(yield* Deferred.await(handled)); - }), - ), + yield* instance.start; + assert.isTrue(yield* Deferred.await(handled)); + }), ); it.effect("stops the scoped process with output still pending", () => - Effect.scoped( - Effect.gen(function* () { - let startCount = 0; - let closedCount = 0; - const closed = yield* Deferred.make(); - const teardownStarted = yield* Deferred.make(); - const finishTeardown = yield* Deferred.make(); - const startedPids = yield* Queue.unbounded(); - const ready = yield* Deferred.make(); - const backendReadyFlag = yield* Ref.make(false); - let shutdownCount = 0; - let persistedFailureCount = 0; - let discardedSessionCount = 0; - let removedTelemetrySources = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - startCount += 1; - yield* Queue.offer(startedPids, 123); - const close = Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishTeardown)), - Effect.andThen( - Effect.sync(() => { - closedCount += 1; - }), - ), - Effect.andThen(Deferred.succeed(closed, void 0)), - Effect.asVoid, - ); + Effect.gen(function* () { + let startCount = 0; + let closedCount = 0; + const closed = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const finishTeardown = yield* Deferred.make(); + const startedPids = yield* Queue.unbounded(); + const ready = yield* Deferred.make(); + const backendReadyFlag = yield* Ref.make(false); + let shutdownCount = 0; + let persistedFailureCount = 0; + let discardedSessionCount = 0; + let removedTelemetrySources = 0; - yield* Scope.addFinalizer(scope, close); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + startCount += 1; + yield* Queue.offer(startedPids, 123); + const close = Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishTeardown)), + Effect.andThen( + Effect.sync(() => { + closedCount += 1; + }), + ), + Effect.andThen(Deferred.succeed(closed, void 0)), + Effect.asVoid, + ); + + yield* Scope.addFinalizer(scope, close); + + return makeProcess({ + stdout: Stream.never, + exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + kill: () => close, + }); + }), + ), + ); - return makeProcess({ - stdout: Stream.never, - exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - kill: () => close, - }); + const instance = yield* makeTestInstance({ + spawnerLayer: layerSpawner, + onReady: Ref.set(backendReadyFlag, true).pipe( + Effect.andThen(Deferred.succeed(ready, void 0)), + Effect.asVoid, + ), + onShutdown: Ref.set(backendReadyFlag, false).pipe( + Effect.andThen( + Effect.sync(() => { + shutdownCount += 1; }), ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - onReady: Ref.set(backendReadyFlag, true).pipe( - Effect.andThen(Deferred.succeed(ready, void 0)), - Effect.asVoid, - ), - onShutdown: Ref.set(backendReadyFlag, false).pipe( - Effect.andThen( - Effect.sync(() => { - shutdownCount += 1; - }), - ), - ), - backendOutputLog: { - persistFailure: () => - Effect.sync(() => { - persistedFailureCount += 1; - }), - discardSession: Effect.sync(() => { - discardedSessionCount += 1; + ), + backendOutputLog: { + persistFailure: () => + Effect.sync(() => { + persistedFailureCount += 1; }), - }, - desktopTelemetryPublisher: { - removeControlSource: () => - Effect.sync(() => { - removedTelemetrySources += 1; - }), - }, - }); - assert.isTrue(Option.isNone(yield* instance.currentConfig)); - - yield* instance.start; - assert.equal(yield* Queue.take(startedPids), 123); - yield* Deferred.await(ready); - assert.isTrue(yield* Ref.get(backendReadyFlag)); - assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig)); - - const runningSnapshot = yield* instance.snapshot; - assert.equal(runningSnapshot.ready, true); - assert.deepEqual(runningSnapshot.activePid, Option.some(123)); - - const stopFiber = yield* instance.stop().pipe(Effect.forkChild); - yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second")); - assert.isFalse(yield* Ref.get(backendReadyFlag)); - assert.equal(shutdownCount, 1); - yield* Deferred.succeed(finishTeardown, undefined); - yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); - assert.equal(startCount, 1); - assert.equal(closedCount, 1); - assert.equal(persistedFailureCount, 0); - assert.equal(discardedSessionCount, 1); - assert.equal(removedTelemetrySources, 1); - - const stoppedSnapshot = yield* instance.snapshot; - assert.isFalse(yield* Ref.get(backendReadyFlag)); - assert.equal(shutdownCount, 1); - assert.equal(stoppedSnapshot.desiredRunning, false); - assert.equal(stoppedSnapshot.ready, false); - assert.equal(Option.isNone(stoppedSnapshot.activePid), true); - }), - ), + discardSession: Effect.sync(() => { + discardedSessionCount += 1; + }), + }, + desktopTelemetryPublisher: { + removeControlSource: () => + Effect.sync(() => { + removedTelemetrySources += 1; + }), + }, + }); + assert.isTrue(Option.isNone(yield* instance.currentConfig)); + + yield* instance.start; + assert.equal(yield* Queue.take(startedPids), 123); + yield* Deferred.await(ready); + assert.isTrue(yield* Ref.get(backendReadyFlag)); + assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig)); + + const runningSnapshot = yield* instance.snapshot; + assert.equal(runningSnapshot.ready, true); + assert.deepEqual(runningSnapshot.activePid, Option.some(123)); + + const stopFiber = yield* instance.stop().pipe(Effect.forkChild); + yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second")); + assert.isFalse(yield* Ref.get(backendReadyFlag)); + assert.equal(shutdownCount, 1); + yield* Deferred.succeed(finishTeardown, undefined); + yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); + assert.equal(startCount, 1); + assert.equal(closedCount, 1); + assert.equal(persistedFailureCount, 0); + assert.equal(discardedSessionCount, 1); + assert.equal(removedTelemetrySources, 1); + + const stoppedSnapshot = yield* instance.snapshot; + assert.isFalse(yield* Ref.get(backendReadyFlag)); + assert.equal(shutdownCount, 1); + assert.equal(stoppedSnapshot.desiredRunning, false); + assert.equal(stoppedSnapshot.ready, false); + assert.equal(Option.isNone(stoppedSnapshot.activePid), true); + }), ); it.effect("restarts when start is requested during stop teardown", () => - Effect.scoped( - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const teardownStarted = yield* Deferred.make(); - const finishTeardown = yield* Deferred.make(); - let startCount = 0; + Effect.gen(function* () { + const starts = yield* Queue.unbounded(); + const teardownStarted = yield* Deferred.make(); + const finishTeardown = yield* Deferred.make(); + let startCount = 0; - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - const closed = yield* Deferred.make(); - startCount += 1; - yield* Queue.offer(starts, startCount); - if (startCount === 1) { - yield* Scope.addFinalizer( - scope, - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishTeardown)), - Effect.andThen(Deferred.succeed(closed, undefined)), - Effect.asVoid, - ), - ); - } else { - yield* Scope.addFinalizer( - scope, - Deferred.succeed(closed, undefined).pipe(Effect.asVoid), - ); - } - return makeProcess({ - exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - ), - ); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + const closed = yield* Deferred.make(); + startCount += 1; + yield* Queue.offer(starts, startCount); + if (startCount === 1) { + yield* Scope.addFinalizer( + scope, + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishTeardown)), + Effect.andThen(Deferred.succeed(closed, undefined)), + Effect.asVoid, + ), + ); + } else { + yield* Scope.addFinalizer( + scope, + Deferred.succeed(closed, undefined).pipe(Effect.asVoid), + ); + } + return makeProcess({ + exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + }); + }), + ), + ); - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - }); + const instance = yield* makeTestInstance({ + spawnerLayer: layerSpawner, + httpClientLayer: layerHttpClient(() => Effect.never), + }); - yield* instance.start; - assert.equal(yield* Queue.take(starts), 1); + yield* instance.start; + assert.equal(yield* Queue.take(starts), 1); - const stopFiber = yield* instance.stop().pipe(Effect.forkChild); - yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second")); - yield* instance.start; - assert.equal((yield* instance.snapshot).desiredRunning, true); + const stopFiber = yield* instance.stop().pipe(Effect.forkChild); + yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second")); + yield* instance.start; + assert.equal((yield* instance.snapshot).desiredRunning, true); - yield* Deferred.succeed(finishTeardown, undefined); - yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); - yield* TestClock.adjust(Duration.millis(500)); + yield* Deferred.succeed(finishTeardown, undefined); + yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); + yield* TestClock.adjust(Duration.millis(500)); - assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2); - const restarted = yield* instance.snapshot; - assert.equal(restarted.desiredRunning, true); - assert.deepEqual(restarted.activePid, Option.some(123)); - }).pipe(Effect.provide(TestClock.layer())), - ), + assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2); + const restarted = yield* instance.snapshot; + assert.equal(restarted.desiredRunning, true); + assert.deepEqual(restarted.activePid, Option.some(123)); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("reports state-directory ownership once without scheduling another backend", () => - Effect.scoped( - Effect.gen(function* () { - let startCount = 0; - const refused = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Effect.succeed( - ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED), - ), - }); - }), - ), + Effect.gen(function* () { + let startCount = 0; + const refused = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.sync(() => { + startCount += 1; + return makeProcess({ + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED), + ), + }); + }), ), - httpClientLayer: layerHttpClient(() => Effect.never), - onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* Deferred.await(refused); - const snapshot = yield* instance.snapshot; - assert.isFalse(snapshot.desiredRunning); - assert.isFalse(snapshot.restartScheduled); - yield* TestClock.adjust(Duration.minutes(1)); - assert.equal(startCount, 1); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), + }); + yield* instance.start; + yield* Deferred.await(refused); + const snapshot = yield* instance.snapshot; + assert.isFalse(snapshot.desiredRunning); + assert.isFalse(snapshot.restartScheduled); + yield* TestClock.adjust(Duration.minutes(1)); + assert.equal(startCount, 1); + }).pipe(Effect.provide(TestClock.layer())), ); // A policy refusal is reported on the first exit, since retrying cannot fix it. @@ -637,177 +620,167 @@ describe("DesktopBackendManager", () => { ])( "reports exit $code with the server output after $exits exits", ({ code, exits, managedPolicy }) => - Effect.scoped( - Effect.gen(function* () { - const message = "Error: Cannot find module 'zod/v4' in /Users/René"; - let exitCount = 0; - const firstExit = yield* Deferred.make(); - const reports = yield* Queue.unbounded<{ - readonly exitCount: number; - readonly failure: DesktopBackendManager.BackendStartupFailure; - }>(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut - // lands inside the emoji's surrogate pair. - stderr: Stream.make( - new TextEncoder().encode( - `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`, - ), - new Uint8Array([0xc3]), - new Uint8Array([0xa9]), + Effect.gen(function* () { + const message = "Error: Cannot find module 'zod/v4' in /Users/René"; + let exitCount = 0; + const firstExit = yield* Deferred.make(); + const reports = yield* Queue.unbounded<{ + readonly exitCount: number; + readonly failure: DesktopBackendManager.BackendStartupFailure; + }>(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut + // lands inside the emoji's surrogate pair. + stderr: Stream.make( + new TextEncoder().encode( + `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`, ), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)), - }), - ), + new Uint8Array([0xc3]), + new Uint8Array([0xa9]), + ), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)), + }), ), ), - httpClientLayer: layerHttpClient(() => Effect.never), - backendOutputLog: { - persistFailure: () => { - exitCount += 1; - return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid); - }, + ), + httpClientLayer: layerHttpClient(() => Effect.never), + backendOutputLog: { + persistFailure: () => { + exitCount += 1; + return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid); }, - onStartupFailure: (failure) => - Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* Deferred.await(firstExit); - yield* TestClock.adjust(Duration.minutes(1)); - const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports); - assert.equal(exitsWhenReported, exits); - assert.equal(failure.reason, `The server could not start (code=${code}).`); - assert.equal(failure.managedPolicy, managedPolicy); - assert.isTrue(failure.output.endsWith(message)); - assert.isTrue(failure.output.isWellFormed()); - }).pipe(Effect.provide(TestClock.layer())), - ), + }, + onStartupFailure: (failure) => + Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid), + }); + yield* instance.start; + yield* Deferred.await(firstExit); + yield* TestClock.adjust(Duration.minutes(1)); + const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports); + assert.equal(exitsWhenReported, exits); + assert.equal(failure.reason, `The server could not start (code=${code}).`); + assert.equal(failure.managedPolicy, managedPolicy); + assert.isTrue(failure.output.endsWith(message)); + assert.isTrue(failure.output.isWellFormed()); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("waits out a slow startup and reports one that never becomes ready", () => - Effect.scoped( - Effect.gen(function* () { - const reports = yield* Queue.unbounded(); - const startInstance = ( - status: Ref.Ref, - onReady?: Effect.Effect, - stdout = "", - ) => - makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - exitCode: Effect.never, - stdout: Stream.make(new TextEncoder().encode(stdout)), - }), - ), + Effect.gen(function* () { + const reports = yield* Queue.unbounded(); + const startInstance = (status: Ref.Ref, onReady?: Effect.Effect, stdout = "") => + makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + exitCode: Effect.never, + stdout: Stream.make(new TextEncoder().encode(stdout)), + }), ), ), - httpClientLayer: layerHttpClient((request) => - Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))), - ), - onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid), - ...(onReady ? { onReady } : {}), - }).pipe(Effect.tap((instance) => instance.start)); - - const slowStatus = yield* Ref.make(503); - const ready = yield* Deferred.make(); - yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid)); - yield* TestClock.adjust(Duration.seconds(66)); - yield* Ref.set(slowStatus, 200); - yield* TestClock.adjust(Duration.millis(100)); - yield* Deferred.await(ready); - assert.isTrue(Option.isNone(yield* Queue.poll(reports))); - - const migratingStatus = yield* Ref.make(503); - const migrated = yield* Deferred.make(); - yield* startInstance( - migratingStatus, - Deferred.succeed(migrated, undefined).pipe(Effect.asVoid), - // Enough progress lines that the start line scrolls out of the output tail. - `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` + - Array.from( - { length: 80 }, - (_, index) => - `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`, - ).join(""), - ); - yield* TestClock.adjust(Duration.minutes(10)); - assert.isTrue(Option.isNone(yield* Queue.poll(reports))); - yield* Ref.set(migratingStatus, 200); - yield* TestClock.adjust(Duration.millis(100)); - yield* Deferred.await(migrated); - - yield* startInstance( - yield* Ref.make(503), - undefined, - `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`, - ); - yield* TestClock.adjust(Duration.seconds(179)); - assert.isTrue(Option.isNone(yield* Queue.poll(reports))); - yield* TestClock.adjust(Duration.seconds(1)); - const failure = yield* Queue.take(reports); - assert.equal(failure.reason, "The server started but did not become ready in time."); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient((request) => + Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))), + ), + onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid), + ...(onReady ? { onReady } : {}), + }).pipe(Effect.tap((instance) => instance.start)); + + const slowStatus = yield* Ref.make(503); + const ready = yield* Deferred.make(); + yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid)); + yield* TestClock.adjust(Duration.seconds(66)); + yield* Ref.set(slowStatus, 200); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(ready); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + + const migratingStatus = yield* Ref.make(503); + const migrated = yield* Deferred.make(); + yield* startInstance( + migratingStatus, + Deferred.succeed(migrated, undefined).pipe(Effect.asVoid), + // Enough progress lines that the start line scrolls out of the output tail. + `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` + + Array.from( + { length: 80 }, + (_, index) => + `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`, + ).join(""), + ); + yield* TestClock.adjust(Duration.minutes(10)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* Ref.set(migratingStatus, 200); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(migrated); + + yield* startInstance( + yield* Ref.make(503), + undefined, + `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`, + ); + yield* TestClock.adjust(Duration.seconds(179)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* TestClock.adjust(Duration.seconds(1)); + const failure = yield* Queue.take(reports); + assert.equal(failure.reason, "The server started but did not become ready in time."); + }).pipe(Effect.provide(TestClock.layer())), ); it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () => - Effect.scoped( - Effect.gen(function* () { - const spawned = yield* Deferred.make(); - const teardownStarted = yield* Deferred.make(); - const teardownFinished = yield* Deferred.make(); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - yield* Deferred.succeed(spawned, undefined); - yield* Scope.addFinalizer( - scope, - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Effect.sleep(Duration.seconds(10))), - Effect.andThen(Deferred.succeed(teardownFinished, undefined)), - Effect.asVoid, - ), - ); - return makeProcess({ - exitCode: Deferred.await(teardownFinished).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - }); - }), - ), + Effect.gen(function* () { + const spawned = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const teardownFinished = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + yield* Deferred.succeed(spawned, undefined); + yield* Scope.addFinalizer( + scope, + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Effect.sleep(Duration.seconds(10))), + Effect.andThen(Deferred.succeed(teardownFinished, undefined)), + Effect.asVoid, + ), + ); + return makeProcess({ + exitCode: Deferred.await(teardownFinished).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }); + }), ), - httpClientLayer: layerHttpClient(() => Effect.never), - }); - yield* instance.start; - yield* Deferred.await(spawned); - - // App quit and the updater stop every backend with this deadline. - const quitDone = yield* Deferred.make(); - const quitFiber = yield* instance - .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) - .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); - - yield* Deferred.await(teardownStarted); - // Past the quit deadline, quit must still wait for the backend to exit. - yield* TestClock.adjust(Duration.seconds(9)); - assert.isFalse(yield* Deferred.isDone(quitDone)); - - yield* TestClock.adjust(Duration.seconds(1)); - yield* Fiber.join(quitFiber); - assert.isTrue(yield* Deferred.isDone(teardownFinished)); - }).pipe(Effect.provide(TestClock.layer())), - ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + }); + yield* instance.start; + yield* Deferred.await(spawned); + + // App quit and the updater stop every backend with this deadline. + const quitDone = yield* Deferred.make(); + const quitFiber = yield* instance + .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) + .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); + + yield* Deferred.await(teardownStarted); + // Past the quit deadline, quit must still wait for the backend to exit. + yield* TestClock.adjust(Duration.seconds(9)); + assert.isFalse(yield* Deferred.isDone(quitDone)); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* Fiber.join(quitFiber); + assert.isTrue(yield* Deferred.isDone(teardownFinished)); + }).pipe(Effect.provide(TestClock.layer())), ); }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 3f7d690eab3d3..8e9f4320c08c7 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -324,61 +324,6 @@ describe("DesktopBackendPool", () => { it.effect( "keeps the update marker after HTTP readiness until the backend publishes its runtime", () => - Effect.scoped( - Effect.gen(function* () { - const fixture = yield* makeUpdateMarkerFixture(); - yield* Effect.gen(function* () { - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const primary = yield* pool.primary; - yield* primary.start; - yield* Deferred.succeed(fixture.allowReady, undefined); - yield* Queue.take(fixture.readyRuns); - assert.isTrue( - fixture.files.has(markerPath), - "a launcher could neither wait nor adopt between readiness and publication", - ); - yield* Deferred.await(fixture.runtimeChecked); - yield* TestClock.adjust(Duration.seconds(5)); - assert.isTrue(fixture.files.has(markerPath)); - fixture.publishRuntime(456); - yield* TestClock.adjust(Duration.seconds(1)); - assert.isTrue( - fixture.files.has(markerPath), - "another process's runtime is not the replacement", - ); - fixture.publishRuntime(123); - yield* TestClock.adjust(Duration.seconds(1)); - yield* Deferred.await(fixture.markerRemoved); - assert.deepEqual(fixture.removed, [markerPath]); - }).pipe(Effect.provide(fixture.layer)); - }), - ), - ); - - it.effect("leaves a replacement update marker written while an earlier wait is pending", () => - Effect.scoped( - Effect.gen(function* () { - const fixture = yield* makeUpdateMarkerFixture(); - yield* Effect.gen(function* () { - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const primary = yield* pool.primary; - yield* primary.start; - yield* Deferred.succeed(fixture.allowReady, undefined); - yield* Queue.take(fixture.readyRuns); - yield* Deferred.await(fixture.runtimeChecked); - yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000)); - const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 }); - fixture.files.set(markerPath, replacement); - yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)); - assert.equal(fixture.files.get(markerPath), replacement); - assert.deepEqual(fixture.removed, []); - }).pipe(Effect.provide(fixture.layer)); - }), - ), - ); - - it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () => - Effect.scoped( Effect.gen(function* () { const fixture = yield* makeUpdateMarkerFixture(); yield* Effect.gen(function* () { @@ -387,105 +332,150 @@ describe("DesktopBackendPool", () => { yield* primary.start; yield* Deferred.succeed(fixture.allowReady, undefined); yield* Queue.take(fixture.readyRuns); + assert.isTrue( + fixture.files.has(markerPath), + "a launcher could neither wait nor adopt between readiness and publication", + ); yield* Deferred.await(fixture.runtimeChecked); - yield* TestClock.adjust(Duration.seconds(30)); - yield* primary.stop(); - yield* primary.start; - yield* Queue.take(fixture.readyRuns); - yield* TestClock.adjust(Duration.seconds(31)); + yield* TestClock.adjust(Duration.seconds(5)); + assert.isTrue(fixture.files.has(markerPath)); + fixture.publishRuntime(456); + yield* TestClock.adjust(Duration.seconds(1)); assert.isTrue( fixture.files.has(markerPath), - "the earlier run's wait must not end the later run's handoff", + "another process's runtime is not the replacement", ); - assert.deepEqual(fixture.removed, []); - fixture.publishRuntime(124); - yield* TestClock.adjust(Duration.millis(100)); + fixture.publishRuntime(123); + yield* TestClock.adjust(Duration.seconds(1)); yield* Deferred.await(fixture.markerRemoved); assert.deepEqual(fixture.removed, [markerPath]); }).pipe(Effect.provide(fixture.layer)); }), - ), ); - it.effect("unregister during pool quit does not interrupt sibling stops", () => - Effect.scoped( - Effect.gen(function* () { - const backend = yield* makeFakeBackendProcess(); - yield* Effect.gen(function* () { - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); - const ready = yield* Deferred.make(); - const siblingStarted = yield* Deferred.make(); - const finishSibling = yield* Deferred.make(); - let siblingCompleted = false; - const instance = yield* pool.register({ - id, - label: Effect.succeed("WSL (Ubuntu)"), - configResolve: Effect.succeed(runningConfig), - onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid), - }); - yield* instance.start; - yield* backend.started; - yield* Deferred.await(ready); - const quitFiber = yield* Effect.all( - [ - instance.stop({ timeout: Duration.seconds(5) }), - Deferred.succeed(siblingStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSibling)), - Effect.andThen( - Effect.sync(() => { - siblingCompleted = true; - }), - ), - ), - ], - { concurrency: "unbounded" }, - ).pipe(Effect.forkChild); - yield* Deferred.await(siblingStarted); - assert.equal(yield* Queue.take(backend.signals), "SIGTERM"); - const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild); - yield* TestClock.adjust(Duration.seconds(5)); - assert.equal(yield* Queue.take(backend.signals), "SIGKILL"); - assert.isUndefined(quitFiber.pollUnsafe()); - assert.isUndefined(unregisterFiber.pollUnsafe()); - assert.isTrue(yield* backend.isRunning); - yield* TestClock.adjust(backend.killWait); - yield* Fiber.join(unregisterFiber); - yield* Deferred.succeed(finishSibling, undefined); - yield* Fiber.join(quitFiber); + it.effect("leaves a replacement update marker written while an earlier wait is pending", () => + Effect.gen(function* () { + const fixture = yield* makeUpdateMarkerFixture(); + yield* Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primary = yield* pool.primary; + yield* primary.start; + yield* Deferred.succeed(fixture.allowReady, undefined); + yield* Queue.take(fixture.readyRuns); + yield* Deferred.await(fixture.runtimeChecked); + yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000)); + const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 }); + fixture.files.set(markerPath, replacement); + yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)); + assert.equal(fixture.files.get(markerPath), replacement); + assert.deepEqual(fixture.removed, []); + }).pipe(Effect.provide(fixture.layer)); + }), + ); - assert.isTrue(siblingCompleted); - assert.isFalse(yield* backend.isRunning); - assert.isTrue(Option.isNone((yield* instance.snapshot).activePid)); - assert.isTrue(Option.isNone(yield* pool.get(id))); - }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend }))); - }), - ), + it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () => + Effect.gen(function* () { + const fixture = yield* makeUpdateMarkerFixture(); + yield* Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const primary = yield* pool.primary; + yield* primary.start; + yield* Deferred.succeed(fixture.allowReady, undefined); + yield* Queue.take(fixture.readyRuns); + yield* Deferred.await(fixture.runtimeChecked); + yield* TestClock.adjust(Duration.seconds(30)); + yield* primary.stop(); + yield* primary.start; + yield* Queue.take(fixture.readyRuns); + yield* TestClock.adjust(Duration.seconds(31)); + assert.isTrue( + fixture.files.has(markerPath), + "the earlier run's wait must not end the later run's handoff", + ); + assert.deepEqual(fixture.removed, []); + fixture.publishRuntime(124); + yield* TestClock.adjust(Duration.millis(100)); + yield* Deferred.await(fixture.markerRemoved); + assert.deepEqual(fixture.removed, [markerPath]); + }).pipe(Effect.provide(fixture.layer)); + }), ); - it.effect("unregister stops the registered instance", () => - Effect.scoped( - Effect.gen(function* () { - const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + it.effect("unregister during pool quit does not interrupt sibling stops", () => + Effect.gen(function* () { + const backend = yield* makeFakeBackendProcess(); + yield* Effect.gen(function* () { const pool = yield* DesktopBackendPool.DesktopBackendPool; + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + const ready = yield* Deferred.make(); + const siblingStarted = yield* Deferred.make(); + const finishSibling = yield* Deferred.make(); + let siblingCompleted = false; const instance = yield* pool.register({ id, label: Effect.succeed("WSL (Ubuntu)"), - configResolve: Effect.succeed({ - ...runningConfig, - preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), - }), + configResolve: Effect.succeed(runningConfig), + onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid), }); yield* instance.start; - assert.equal((yield* instance.snapshot).restartScheduled, true); + yield* backend.started; + yield* Deferred.await(ready); + const quitFiber = yield* Effect.all( + [ + instance.stop({ timeout: Duration.seconds(5) }), + Deferred.succeed(siblingStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSibling)), + Effect.andThen( + Effect.sync(() => { + siblingCompleted = true; + }), + ), + ), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.forkChild); + yield* Deferred.await(siblingStarted); + assert.equal(yield* Queue.take(backend.signals), "SIGTERM"); + const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(5)); + assert.equal(yield* Queue.take(backend.signals), "SIGKILL"); + assert.isUndefined(quitFiber.pollUnsafe()); + assert.isUndefined(unregisterFiber.pollUnsafe()); + assert.isTrue(yield* backend.isRunning); + yield* TestClock.adjust(backend.killWait); + yield* Fiber.join(unregisterFiber); + yield* Deferred.succeed(finishSibling, undefined); + yield* Fiber.join(quitFiber); - yield* pool.unregister(id); + assert.isTrue(siblingCompleted); + assert.isFalse(yield* backend.isRunning); + assert.isTrue(Option.isNone((yield* instance.snapshot).activePid)); + assert.isTrue(Option.isNone(yield* pool.get(id))); + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend }))); + }), + ); - const stopped = yield* instance.snapshot; - assert.equal(stopped.desiredRunning, false); - assert.equal(stopped.restartScheduled, false); - assert.equal(Option.isNone(yield* pool.get(id)), true); - }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))), - ), + it.effect("unregister stops the registered instance", () => + Effect.gen(function* () { + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const instance = yield* pool.register({ + id, + label: Effect.succeed("WSL (Ubuntu)"), + configResolve: Effect.succeed({ + ...runningConfig, + preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), + }), + }); + yield* instance.start; + assert.equal((yield* instance.snapshot).restartScheduled, true); + + yield* pool.unregister(id); + + const stopped = yield* instance.snapshot; + assert.equal(stopped.desiredRunning, false); + assert.equal(stopped.restartScheduled, false); + assert.equal(Option.isNone(yield* pool.get(id)), true); + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))), ); }); diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts index aec3a2d5b45c0..b0cf4823126e2 100644 --- a/apps/desktop/src/electron/ElectronProtocol.test.ts +++ b/apps/desktop/src/electron/ElectronProtocol.test.ts @@ -63,7 +63,7 @@ describe("ElectronProtocol", () => { assert.equal((yield* request("/%invalid")).status, 400); assert.equal((yield* request("/", { method: "POST" })).status, 405); assert.equal(netFetchMock.mock.calls.length, 0); - }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer)), Effect.scoped), + }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer))), ); it.effect("proxies the stable renderer origin to the current app server", () => diff --git a/apps/desktop/src/electron/ElectronTheme.test.ts b/apps/desktop/src/electron/ElectronTheme.test.ts index 4239bfe4c5bca..47aa0ce1f8df8 100644 --- a/apps/desktop/src/electron/ElectronTheme.test.ts +++ b/apps/desktop/src/electron/ElectronTheme.test.ts @@ -42,7 +42,7 @@ describe("ElectronTheme", () => { assert.equal(nativeTheme.themeSource, "light"); portal.report(null); assert.equal(nativeTheme.themeSource, "system"); - }).pipe(Effect.scoped), + }), ); it.effect("keeps an explicit appearance over the desktop color scheme", () => @@ -57,7 +57,7 @@ describe("ElectronTheme", () => { yield* theme.setSource("system"); assert.equal(nativeTheme.themeSource, "dark"); - }).pipe(Effect.scoped), + }), ); it.effect("stops following the desktop when the layer is released", () => @@ -76,6 +76,6 @@ describe("ElectronTheme", () => { }); yield* theme.setSource("system"); assert.equal(nativeTheme.themeSource, "system"); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts index 45f63b951f366..1973ab49cefeb 100644 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -63,5 +63,5 @@ it.effect("answers only the main window's top frame", () => appSubframe: ["rejected", undefined], previewGuest: ["rejected", undefined], }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 80053c78caee4..0e422f9bc7356 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -88,6 +88,7 @@ export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webvie export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate"; export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back"; export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward"; +export const PREVIEW_STOP_LOADING_CHANNEL = "desktop:preview-stop-loading"; export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh"; export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in"; export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index ea291b66b3149..cc810fee072ad 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -168,6 +168,11 @@ const refresh = tabMethod( "desktop.ipc.preview.refresh", (manager, tabId) => manager.refresh(tabId), ); +const stopLoading = tabMethod( + IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, + "desktop.ipc.preview.stopLoading", + (manager, tabId) => manager.stopLoading(tabId), +); const zoomIn = tabMethod( IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, "desktop.ipc.preview.zoomIn", @@ -472,6 +477,7 @@ export const methods = [ goBack, goForward, refresh, + stopLoading, zoomIn, zoomOut, resetZoom, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index a538b821ff77c..6414743ac3b2f 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -389,6 +389,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }), goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }), refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }), + stopLoading: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, { tabId }), zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }), zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }), resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }), diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 6309c4ea993f1..484ba6f9358f6 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts @@ -89,7 +89,7 @@ describe("BrowserImport.importCookies", () => { assert.instanceOf(error, BrowserImport.BrowserImportFailedError); assert.equal(error.reason, "unknownSourceProfile"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect.skipIf(!symlinksSupported)( @@ -114,7 +114,7 @@ describe("BrowserImport.importCookies", () => { assert.instanceOf(error, BrowserImport.BrowserImportFailedError); assert.equal(error.reason, "browserRunning"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts index e5aa05f268e43..92ab35320dab7 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts @@ -134,7 +134,7 @@ describe("readChromiumCookieDatabase", () => { const partitioned = yield* readChromiumCookieDatabase(filename, keys, "linux"); expect(partitioned.cookies).toEqual([]); expect(partitioned.undecryptable).toBe(1); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () => @@ -186,7 +186,7 @@ describe("readChromiumCookieDatabase", () => { { name: "encrypted", value: "stored encrypted" }, { name: "empty", value: "" }, ]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("enforces domain binding only for schema 24 and newer", () => @@ -227,7 +227,7 @@ describe("readChromiumCookieDatabase", () => { ]); expect(result.undecryptable).toBe(2); expect(result.undecryptableHosts).toEqual(["wrong.example", "short.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("decrypts mixed v10 and v11 cookies with their respective keys", () => @@ -273,7 +273,7 @@ describe("readChromiumCookieDatabase", () => { ]); expect(v10Only.undecryptable).toBe(1); expect(v10Only.undecryptableHosts).toEqual(["v11.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("recovers records written with the empty-passphrase key", () => @@ -320,7 +320,7 @@ describe("readChromiumCookieDatabase", () => { const noV11 = yield* readChromiumCookieDatabase(filename, { cbcV10, cbcEmpty }, "linux"); expect(noV11.cookies.map(({ name }) => name)).toEqual(["empty-v10"]); expect(noV11.undecryptableHosts).toEqual(["ev11.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("treats unversioned encrypted values as legacy plaintext on macOS and Linux", () => @@ -355,7 +355,7 @@ describe("readChromiumCookieDatabase", () => { expect(mac.undecryptable).toBe(0); expect(linux.cookies[0]?.value).toBe("legacy cleartext"); expect(linux.undecryptable).toBe(0); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () => @@ -409,6 +409,6 @@ describe("readChromiumCookieDatabase", () => { expect(chips.cookies.map(({ name }) => name)).toEqual(["plain"]); expect(chips.undecryptable).toBe(1); expect(chips.undecryptableHosts).toEqual(["partitioned.example"]); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts index 402397d3fde60..ca0a86cedacd3 100644 --- a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts +++ b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts @@ -11,7 +11,7 @@ import { snapshotCookieDatabase } from "./CookieDatabase.ts"; const runNode = ( effect: Effect.Effect, -) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); +) => effect.pipe(Effect.provide(NodeServices.layer)); describe("snapshotCookieDatabase", () => { it.effect("includes committed WAL data in one consistent database", () => diff --git a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts index be41318fa01e6..33e32ec030be3 100644 --- a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts @@ -78,7 +78,7 @@ const writeFirefoxCookieDatabase = Effect.fnUntraced(function* ( }); const run = (effect: Effect.Effect) => - effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); + effect.pipe(Effect.provide(NodeServices.layer)); describe("readFirefoxCookies", () => { it.effect("converts millisecond expiries from schema 16 and newer", () => diff --git a/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts b/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts index 8358088bc1344..8ef376e4887bf 100644 --- a/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts +++ b/apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts @@ -64,6 +64,6 @@ it.layer(NodeServices.layer)("Linux browser secret path", (it) => { assert.isUndefined(yield* resolve(false, "win32")); yield* fileSystem.remove(staged); assert.isUndefined(yield* resolve(false)); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts index 7e92334c957de..f82f2319baeb7 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts @@ -240,7 +240,7 @@ describe("safariAccessDenied", () => { yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b])); assert.isFalse(yield* safariAccessDenied(jar)); assert.isFalse(yield* safariAccessDenied(`${directory}/absent.binarycookies`)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts b/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts index 3b33f872d124d..dc225b04bac72 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts @@ -39,7 +39,7 @@ it.effect("detects Safari access becoming available without reading or importing assert.isTrue(yield* Effect.promise(check)); yield* fs.remove(jar); assert.isFalse(yield* Effect.promise(check)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("recognizes access when cookies exist only in a named Safari profile", () => @@ -55,5 +55,5 @@ it.effect("recognizes access when cookies exist only in a named Safari profile", yield* fs.makeDirectory(directory, { recursive: true }); yield* fs.writeFileString(`${directory}/Cookies.binarycookies`, "not parsed"); assert.isTrue(yield* Effect.promise(check)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 720a57e64a9dc..9b2c3cb26c8f7 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -51,7 +51,7 @@ const run = ( E, FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner >, -) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped); +) => effect.pipe(Effect.provide(NodeServices.layer)); const writeCookieDatabase = (file: string, count: number) => Effect.sync(() => { diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index 6e657ba5fc4d7..ccc2b868720b4 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -16,6 +16,7 @@ const makeTarget = ( title: () => "Fixture", userAgent: () => "Electron", setDownloadDirectory, + receivesScreencast: () => true, }); const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) => diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 94a78f47db686..658e1cf70623d 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -9,6 +9,8 @@ export interface CdpRelayTarget { owner?: string, ) => Promise; readonly sessionDetached?: (owner: string) => void; + /** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */ + readonly receivesScreencast: (owner: string | undefined) => boolean; /** The page's own CDP target id; Playwright keys the main frame by it. */ readonly targetId: () => Promise; readonly url: () => string; @@ -260,8 +262,15 @@ export function createCdpRelayConnection( send({ method, params, sessionId }); return; } - for (const [id, kind] of sessions) - if (kind === "page") send({ method, params, sessionId: id }); + for (const [id, kind] of sessions) { + if (kind !== "page") continue; + if ( + method === "Page.screencastFrame" && + !target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id) + ) + continue; + send({ method, params, sessionId: id }); + } }, }; } diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 94809f0d10cfa..393e4cccccf9c 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -16,6 +16,15 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const decodeCdpReply = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ id: Schema.Number })), ); +const decodeCdpMessage = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + id: Schema.optional(Schema.Number), + method: Schema.optional(Schema.String), + sessionId: Schema.optional(Schema.String), + }), + ), +); const key = { threadId: "thread-1", tabId: "tab-1" }; /** Sends a page command whose id the fake debugger records as it receives it. */ const command = ( @@ -43,6 +52,8 @@ const makeDebuggee = ( const pending: Array<() => void> = []; const focusChanges: Array<() => void> = []; const sent: Array = []; + const methods: Array = []; + const rejects: Array<() => void> = []; const sendWaiters: Array<() => void> = []; const focusEmulation: Array = []; const debuggee = Object.assign(emitter, { @@ -67,6 +78,8 @@ const makeDebuggee = ( return; } sent.push(params?.id); + methods.push(method); + rejects.push(() => reject(new Error("Refused"))); pending.push(() => resolve({ method })); sendWaiters.shift()?.(); }), @@ -94,6 +107,10 @@ const makeDebuggee = ( webContents.emit("did-fail-load", {}, code, "Failed", "http://localhost/", true), /** Ids of the commands the debugger received, in order. */ sent, + /** Methods of the same commands, in order. */ + methods, + /** Refuses the pending command the debugger received with this id. */ + refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), @@ -116,16 +133,24 @@ const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], coun /** * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe - * before sending commands: a new subscriber releases the tab's relay. + * before sending commands: a new subscriber releases the tab's relay. Screencast frames + * go to `frames` by the session they were sent to. */ -const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) => +const watchReplies = ( + host: DesktopBrowserHost.DesktopBrowserHost["Service"], + frames: Array = [], +) => Effect.gen(function* () { const replies = yield* Queue.unbounded(); yield* host.events.pipe( Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), - Stream.runForEach((event) => - event.type === "cdp" ? Queue.offer(replies, decodeCdpReply(event.message).id) : Effect.void, - ), + Stream.runForEach((event) => { + if (event.type !== "cdp") return Effect.void; + const { id, method, sessionId } = decodeCdpMessage(event.message); + if (id !== undefined) return Queue.offer(replies, id); + if (method === "Page.screencastFrame") frames.push(sessionId); + return Effect.void; + }), Effect.forkScoped, ); yield* Effect.yieldNow; @@ -283,7 +308,7 @@ describe("DesktopBrowserHost", () => { expect(reply).toMatchObject({ type: "cdp" }); expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2); - }).pipe(Effect.scoped), + }), ); it.effect("sends a page one screenshot at a time", () => @@ -302,7 +327,7 @@ describe("DesktopBrowserHost", () => { debuggee.releaseFirst(); expect(yield* Queue.take(replies)).toBe(1); expect(debuggee.sent).toEqual([1, 3, 2]); - }).pipe(Effect.scoped), + }), ); it.effect("stops waiting on a screenshot the page navigated away from", () => @@ -327,7 +352,7 @@ describe("DesktopBrowserHost", () => { debuggee.releaseFirst(); expect(yield* Queue.take(replies)).toBe(2); expect(debuggee.sent).toEqual([1, 2, 3]); - }).pipe(Effect.scoped), + }), ); it.effect("drops screenshots a released relay left waiting", () => @@ -399,7 +424,7 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(1); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () => @@ -587,7 +612,7 @@ describe("DesktopBrowserHost", () => { yield* turn(false); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false, true]); - }).pipe(Effect.scoped), + }), ); it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () => @@ -625,7 +650,7 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(4); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("stops painting for a queued screenshot once its session detaches", () => @@ -664,7 +689,7 @@ describe("DesktopBrowserHost", () => { expect(painting).toEqual([true, false]); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("never sends a screenshot whose session detached while focus was changing", () => @@ -688,7 +713,7 @@ describe("DesktopBrowserHost", () => { debuggee.settleFocus(); yield* settle; expect(debuggee.sent).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () => @@ -718,7 +743,7 @@ describe("DesktopBrowserHost", () => { debuggee.release(); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () => @@ -739,7 +764,7 @@ describe("DesktopBrowserHost", () => { expect(painting).toEqual([true, false]); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle after a person's input through a viewer that then closed", () => @@ -768,7 +793,7 @@ describe("DesktopBrowserHost", () => { yield* settle; yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("keeps a page's screencast when a child session's screencast is refused", () => @@ -790,7 +815,7 @@ describe("DesktopBrowserHost", () => { expect(yield* Queue.take(replies)).toBe(2); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true]); - }).pipe(Effect.scoped), + }), ); it.effect("ignores a screencast that arrives on a session after it detached", () => @@ -816,7 +841,7 @@ describe("DesktopBrowserHost", () => { yield* settle; yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("lets a guest throttle once the session waiting on its command detaches", () => @@ -843,7 +868,7 @@ describe("DesktopBrowserHost", () => { }); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("never sends a screenshot queued by a session that has since detached", () => @@ -874,7 +899,7 @@ describe("DesktopBrowserHost", () => { yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("keeps a streamed guest focused until its screencast ends", () => @@ -935,7 +960,7 @@ describe("DesktopBrowserHost", () => { }); yield* TestClock.adjust("1 minute"); expect(debuggee.focusEmulation).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("paints a hidden guest only while the screenshot it is taking is pending", () => @@ -961,7 +986,7 @@ describe("DesktopBrowserHost", () => { debuggee.release(); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("stops painting for a screenshot Chromium never answers once its document goes", () => @@ -1006,7 +1031,7 @@ describe("DesktopBrowserHost", () => { host.detach(key); yield* settle; expect(painting).toEqual([true, false, true, false, true, false, true, false]); - }).pipe(Effect.scoped), + }), ); it.effect("paints a streamed guest until its last screencast ends", () => @@ -1037,7 +1062,176 @@ describe("DesktopBrowserHost", () => { }); yield* settle; expect(painting).toEqual([true, false]); - }).pipe(Effect.scoped), + }), + ); + + it.effect("keeps a guest's one screencast running until its last streaming session stops", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const frames: Array = []; + const replies = yield* watchReplies(host, frames); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const nativeStops = () => + debuggee.methods.filter((method) => method === "Page.stopScreencast").length; + + // A viewer and a recording share Chromium's single screencast for the guest. + yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } }); + expect(yield* Queue.take(replies)).toBe(0); + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + debuggee.release(); + yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" }); + yield* settle; + expect(nativeStops(), "stopped the screencast another session still streams").toBe(0); + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 }); + yield* settle; + expect(frames, "sent a stopped or idle session the screencast's frames").toEqual([ + "t3-preview-page-2", + ]); + + yield* raw({ id: 6, method: "Page.stopScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + expect(nativeStops()).toBe(1); + }), + ); + + it.effect("keeps a session's screencast when another of its starts is refused", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const frames: Array = []; + const replies = yield* watchReplies(host, frames); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + + yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } }); + expect(yield* Queue.take(replies)).toBe(0); + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(1); + yield* raw({ + id: 2, + method: "Page.startScreencast", + params: { id: 2 }, + sessionId: "t3-preview-page-1", + }); + yield* raw({ + id: 3, + method: "Page.startScreencast", + params: { id: 3 }, + sessionId: "t3-preview-page-1", + }); + yield* settle; + debuggee.refuse(2); + debuggee.release(); + expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([2, 3]); + yield* settle; + expect(debuggee.methods).not.toContain("Page.stopScreencast"); + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 }); + yield* settle; + expect(frames).toContain("t3-preview-page-1"); + + // A refused replacement leaves the session's running stream, shared with another session. + yield* raw({ id: 4, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(4); + yield* raw({ + id: 5, + method: "Page.startScreencast", + params: { id: 5 }, + sessionId: "t3-preview-page-2", + }); + yield* raw({ + id: 6, + method: "Page.startScreencast", + params: { id: 6 }, + sessionId: "t3-preview-page-1", + }); + yield* settle; + debuggee.refuse(6); + debuggee.release(); + expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([5, 6]); + yield* settle; + frames.length = 0; + debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 }); + yield* settle; + expect(frames).toEqual(["t3-preview-page-1", "t3-preview-page-2"]); + }), + ); + + it.effect("stops a guest's screencast once its last streaming session detaches", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const nativeStops = () => + debuggee.methods.filter((method) => method === "Page.stopScreencast").length; + + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" }); + yield* settle; + debuggee.release(); + // Streamers go without stopping, such as viewers that closed. + yield* raw({ + id: 5, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-1" }, + }); + yield* settle; + expect(nativeStops(), "stopped the screencast another session still streams").toBe(0); + yield* raw({ + id: 6, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-2" }, + }); + const answered = []; + for (let reply = 0; reply < 4; reply++) answered.push(yield* Queue.take(replies)); + expect(answered.toSorted()).toEqual([3, 4, 5, 6]); + yield* settle; + expect(nativeStops()).toBe(1); + }), + ); + + it.effect("stops a screencast whose start lands after its session detached", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee({ deferFocus: true }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(1); + // The start waits on focus emulation while the viewer closes. + yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + yield* raw({ + id: 3, + method: "Target.detachFromTarget", + params: { sessionId: "t3-preview-page-1" }, + }); + expect(yield* Queue.take(replies)).toBe(3); + debuggee.settleFocus(); + yield* settle; + debuggee.release(); + expect(yield* Queue.take(replies)).toBe(2); + yield* settle; + expect(debuggee.methods.at(-1), "left the late screencast running").toBe( + "Page.stopScreencast", + ); + }), ); it.effect("saves a server tab's download under its CDP guid where the server asked", () => @@ -1072,7 +1266,7 @@ describe("DesktopBrowserHost", () => { expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true); expect(paths).toEqual(["/srv/downloads/guid-1"]); expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false); - }).pipe(Effect.scoped), + }), ); it.effect("tells a download the person clicked from one the agent's input started", () => @@ -1170,6 +1364,6 @@ describe("DesktopBrowserHost", () => { expect(JSON.parse((next as { message: string }).message)).toMatchObject({ method: "Page.loadEventFired", }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index a53fc0e3e6ec2..e5f43634d204a 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -75,8 +75,8 @@ interface AttachedTab { */ agentUsed: boolean; focusReleasing: boolean; - /** The sessions streaming the guest; one stopping leaves the others' screencasts running. */ - readonly screencasts: Set; + /** The sessions sharing the guest's one Chromium screencast; it stops with the last of them. */ + readonly screencasts: Map; readonly onMessage: ( event: Electron.Event, method: string, @@ -289,9 +289,15 @@ export const make = Effect.gen(function* () { dropFocusHolds(tab); }; + /** An owner that leaves without stopping would otherwise keep the screencast running unseen. */ + const leaveScreencast = (tab: AttachedTab, owner: string | undefined) => { + if (!tab.screencasts.delete(owner) || tab.screencasts.size > 0) return; + void tab.debuggee.debugger.sendCommand("Page.stopScreencast").catch(() => {}); + }; + /** A detached session, such as a closed viewer, waits on nothing it sent. */ const dropSessionHolds = (tab: AttachedTab, owner: string) => { - tab.screencasts.delete(owner); + leaveScreencast(tab, owner); for (const [pending, holder] of tab.focusPending) { if (holder === owner) tab.focusPending.delete(pending); } @@ -330,13 +336,19 @@ export const make = Effect.gen(function* () { { send: (method, params, sessionId, owner) => { // A child session's screencast is not the page's, such as a late one on a detached session. - if (sessionId === undefined && method === "Page.startScreencast") { - tab.screencasts.add(owner); + const stream = + sessionId === undefined && method === "Page.startScreencast" + ? (tab.screencasts.get(owner) ?? { started: false, pending: 0 }) + : undefined; + if (stream) { + stream.pending += 1; + tab.screencasts.set(owner, stream); if (owner !== undefined) streamingOwners.add(owner); syncPainting(tab); } else if (sessionId === undefined && method === "Page.stopScreencast") { tab.screencasts.delete(owner); syncPainting(tab); + if (tab.screencasts.size > 0) return Promise.resolve({}); } // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's. if ( @@ -365,19 +377,42 @@ export const make = Effect.gen(function* () { held ? holdFocus(tab, owner, () => forward(current)) : forward(current), ) : method === "Page.startScreencast" - ? holdFocus(tab, owner, forward).catch((cause: unknown) => { - // A viewer can outlive a refused stream; nothing is streaming for it. - if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner); - releaseFocusWhenIdle(tab); - syncPainting(tab); - throw cause; - }) + ? holdFocus(tab, owner, forward).then( + (result) => { + if (stream) { + stream.pending -= 1; + stream.started = true; + // A detach's stop can overtake a start still waiting on focus; nobody owns it now. + if (tab.screencasts.get(owner) !== stream && tab.screencasts.size === 0) { + void debuggee.sendCommand("Page.stopScreencast").catch(() => {}); + } + } + return result; + }, + (cause: unknown) => { + if (stream) stream.pending -= 1; + // A viewer can outlive a refused start; its running or pending stream still holds it. + if ( + stream && + !stream.started && + stream.pending === 0 && + tab.relay === relay && + tab.screencasts.get(owner) === stream + ) { + leaveScreencast(tab, owner); + } + releaseFocusWhenIdle(tab); + syncPainting(tab); + throw cause; + }, + ) : holdFocus(tab, owner, forward); }, sessionDetached: (owner) => { detachedOwners.add(owner); dropSessionHolds(tab, owner); }, + receivesScreencast: (owner) => tab.screencasts.has(owner), targetId: () => debuggee .sendCommand("Target.getTargetInfo") @@ -463,7 +498,7 @@ export const make = Effect.gen(function* () { painting: false, agentUsed: false, focusReleasing: false, - screencasts: new Set(), + screencasts: new Map(), onMessage: (_event, method, params, sessionId) => { if (method === "Page.downloadWillBegin") { const guid = (params as { guid?: unknown } | undefined)?.guid; diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index a0889940a6682..48191ce2c4b98 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -44,6 +44,30 @@ describe("preview guest input", () => { expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything()); }); + it("stops the guest navigation without stopping its embedder", async () => { + let guestLoading = true; + let hostLoading = true; + const guest = { + stop: () => { + guestLoading = false; + }, + }; + const debuggee = { + sendCommand: async () => { + hostLoading = false; + return {}; + }, + }; + await sendPageCommand( + guest as unknown as Electron.WebContents, + debuggee as unknown as Electron.Debugger, + "Page.stopLoading", + {}, + ); + expect(guestLoading).toBe(false); + expect(hostLoading).toBe(true); + }); + it.each([ { sessionId: undefined, diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 2af13af8d7daa..4d794beea62bc 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -185,6 +185,10 @@ export const sendPageCommand = async ( else webContents.reload(); return {}; } + if (method === "Page.stopLoading") { + webContents.stop(); + return {}; + } if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) { return debuggee.sendCommand(method, params); } diff --git a/apps/desktop/src/preview/GuestProtocol.ts b/apps/desktop/src/preview/GuestProtocol.ts index 09d4eff6d2013..1d24079d1947f 100644 --- a/apps/desktop/src/preview/GuestProtocol.ts +++ b/apps/desktop/src/preview/GuestProtocol.ts @@ -5,13 +5,16 @@ export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured"; export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme"; export const ANNOTATION_SEND_ENABLED_CHANNEL = "preview:annotation-send-enabled"; export const HUMAN_INPUT_CHANNEL = "preview:human-input"; -export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate"; +// Sent to the hosting element (ipc-message). The web app mirrors this +// literal in HostedBrowserWebview because it cannot import from the desktop app. +export const POINTER_DOWN_HOST_CHANNEL = "preview:pointer-down"; export const PAGE_UNHANDLED_SHORTCUT_CHANNEL = "preview:page-unhandled-shortcut"; export const RECORDING_CURSOR_CHANNEL = "preview:recording-cursor"; export const RECORDING_POINTER_CHANNEL = "preview:recording-pointer"; export const RECORDING_KEY_CHANNEL = "preview:recording-key"; export const RECORDING_INPUT_CHANNEL = "preview:recording-input"; export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller"; +export const THUMB_PRESS_CHANNEL = "preview:thumb-press"; export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create"; export const PASSKEY_GET_CHANNEL = "preview:passkey-get"; export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge"; diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 6db04b389ab6d..530a1200378b1 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -671,7 +671,7 @@ describe("PreviewManager", () => { if (existing) { expect(yield* fs.readFileString(`${downloads}/report.txt`)).toBe("existing download"); } - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped), + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect.each([ @@ -745,6 +745,69 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("keeps mouse back and forward buttons inside the preview tab", () => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const goBack = vi.fn(); + const goForward = vi.fn(); + const send = vi.fn(); + let canGoBack = false; + Object.assign(preview.webContents, { + navigationHistory: { + canGoBack: () => canGoBack, + canGoForward: () => true, + goBack, + goForward, + }, + getZoomFactor: () => 2, + send, + }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_mouse_navigation"); + yield* manager.registerWebview("tab_mouse_navigation", 42); + + // Electron reports thumb buttons as "back"/"forward" for every frame of the guest, iframes included. + const beforeMouse = preview.listeners.get("before-mouse-event"); + expect(beforeMouse, "guest has no before-mouse-event listener").toBeDefined(); + const press = (type: "mouseDown" | "mouseUp", button: string) => { + const preventDefault = vi.fn(); + beforeMouse!({ preventDefault } as never, { type, button, x: 10, y: 10 } as never); + return preventDefault; + }; + + // At the start of tab history the press is still swallowed, or the host app goes back instead. + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + + canGoBack = true; + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).toHaveBeenCalledOnce(); + expect(press("mouseDown", "forward")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "forward")).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + for (const button of ["left", "right"]) { + expect(press("mouseDown", button)).not.toHaveBeenCalled(); + expect(press("mouseUp", button)).not.toHaveBeenCalled(); + } + expect(goBack).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + // The guest replays dropped presses for human input and recordings, in CSS px. + expect(send.mock.calls.filter(([channel]) => channel === "preview:thumb-press")).toEqual([ + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 4], + ["preview:thumb-press", "up", 5, 5, 4], + ]); + }), + ), + ); + effectIt.effect("keeps editing and forwarded shortcuts in whichever tab holds focus", () => withManager((manager) => Effect.gen(function* () { @@ -820,7 +883,7 @@ describe("PreviewManager", () => { ["linux", false], ["win32", false], ] as const)( - "lets the page and its iframes claim the find shortcut before the host opens find on %s", + "lets the page and its iframes claim the find and zoom shortcuts before the host acts on %s", ([platform, usesMeta]) => withManager( (manager) => @@ -838,8 +901,23 @@ describe("PreviewManager", () => { yield* manager.registerWebview("tab_page_find", 42); yield* manager.setForwardedShortcuts([ { command: "preview.find", shortcut: parseKeybindingShortcut("mod+f")! }, + { command: "preview.zoomIn", shortcut: parseKeybindingShortcut("mod+=")! }, ]); const beforeInput = preview.listeners.get("before-input-event")!; + const keepsZoom = vi.fn(); + beforeInput( + { preventDefault: keepsZoom } as never, + { + type: "keyDown", + key: "=", + code: "Equal", + meta: usesMeta, + control: !usesMeta, + shift: false, + alt: false, + } as never, + ); + expect(keepsZoom).not.toHaveBeenCalled(); const findKey = { type: "keyDown", key: "f", @@ -2056,7 +2134,7 @@ describe("PreviewManager", () => { expect(yield* nextType).toBe("attached"); yield* manager.closeTab("tab_1"); expect(yield* nextType).toBe("detached"); - }).pipe(Effect.provide(managerLayer()), Effect.scoped), + }).pipe(Effect.provide(managerLayer())), ); effectIt.effect( @@ -2115,7 +2193,7 @@ describe("PreviewManager", () => { expect(yield* Queue.take(capturing)).toBe(true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); - }).pipe(Effect.provide(managerLayer()), Effect.scoped), + }).pipe(Effect.provide(managerLayer())), ); effectIt.effect("reports early and subsequent load failures for the current guest", () => @@ -2206,7 +2284,7 @@ describe("PreviewManager", () => { expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab }); expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab }); expect(statuses.at(-1)?.kind).toBe("Success"); - }).pipe(Effect.provide(managerLayer()), Effect.scoped), + }).pipe(Effect.provide(managerLayer())), ); effectIt.effect("discards a screenshot that resolves after its guest is replaced", () => diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 189885b9b2178..49b61c73316f3 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -81,13 +81,13 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, RECORDING_POINTER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; @@ -444,6 +444,9 @@ type FindResultListener = (event: DesktopPreviewFindResultEvent) => Effect.Effec const PAGE_FIRST_FORWARDED_COMMANDS: ReadonlySet = new Set([ "preview.find", + "preview.zoomIn", + "preview.zoomOut", + "preview.resetZoom", ]); const decodePageShortcutKeys = Schema.decodeUnknownOption( @@ -1487,15 +1490,27 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const humanInput = (_event: unknown, rawSignal?: unknown): void => { runFork(handleHumanInput(rawSignal)); }; - const mouseNavigate = (_event: unknown, payload?: unknown): void => { - const direction = - typeof payload === "object" && payload !== null && "direction" in payload - ? (payload as { direction?: unknown }).direction - : undefined; - if (direction !== "back" && direction !== "forward") return; + // Chromium navigates the outermost WebContents (the host app) on thumb buttons, even from guest iframes. + const beforeMouse = (event: Electron.Event, mouse: Electron.MouseInputEvent): void => { + // Electron reports thumb buttons as "back" and "forward", which its typings omit. + const button: string | undefined = mouse.button; + if (button !== "back" && button !== "forward") return; + if (mouse.type !== "mouseDown" && mouse.type !== "mouseUp") return; + event.preventDefault(); + // The page never sees the press, so the guest replays it; these coordinates are DIPs, not CSS px. + const zoom = wc.getZoomFactor(); + const phase = mouse.type === "mouseDown" ? "down" : "up"; + wc.send( + THUMB_PRESS_CHANNEL, + phase, + mouse.x / zoom, + mouse.y / zoom, + button === "back" ? 3 : 4, + ); + if (phase !== "up") return; runFork( attempt({ operation: "mouseNavigate", tabId, webContentsId: wc.id }, () => { - if (direction === "back") { + if (button === "back") { if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack(); } else if (wc.navigationHistory.canGoForward()) { wc.navigationHistory.goForward(); @@ -1553,7 +1568,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); if (forwarded && host) { // The page keeps these keys. Only the main-frame preload can report one it - // left unhandled, so a focused iframe (e.g. Google Docs' input) keeps its own find. + // left unhandled, so a focused iframe (e.g. Google Docs' input) keeps its own find or zoom. if (PAGE_FIRST_FORWARDED_COMMANDS.has(forwarded.command)) return; event.preventDefault(); if (!input.isAutoRepeat) { @@ -1605,9 +1620,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.off("found-in-page", foundInPage as never); wc.off("did-create-window", windowCreated); wc.off("before-input-event", beforeInput); + wc.off("before-mouse-event", beforeMouse); wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); }).pipe(Effect.ignore), @@ -1628,7 +1643,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.on("found-in-page", foundInPage as never); wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys = passkeys.attachGuest(wc); wc.setWindowOpenHandler((details) => { @@ -1656,6 +1670,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.on("did-create-window", windowCreated); wc.on("before-input-event", beforeInput); + wc.on("before-mouse-event", beforeMouse); }); yield* Ref.update(attachedRef, (attached) => replaceMap(attached, (copy) => { @@ -2145,6 +2160,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (wc.navigationHistory.canGoForward()) wc.navigationHistory.goForward(); }); const refresh = (tabId: string) => withWebContents("refresh", tabId, (wc) => wc.reload()); + const stopLoading = (tabId: string) => withWebContents("stopLoading", tabId, (wc) => wc.stop()); const hardReload = (tabId: string) => withWebContents("hardReload", tabId, (wc) => wc.reloadIgnoringCache()); const findInPage = ( @@ -3528,6 +3544,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function prepareWebview, reapplyZoom, refresh, + stopLoading, registerWebview, resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR), setZoomFactor: (tabId: string, zoomFactor: number) => @@ -3729,6 +3746,7 @@ export class PreviewManager extends Context.Service< readonly goBack: (tabId: string) => Effect.Effect; readonly goForward: (tabId: string) => Effect.Effect; readonly refresh: (tabId: string) => Effect.Effect; + readonly stopLoading: (tabId: string) => Effect.Effect; readonly zoomIn: (tabId: string) => Effect.Effect; readonly zoomOut: (tabId: string) => Effect.Effect; readonly resetZoom: (tabId: string) => Effect.Effect; @@ -3903,6 +3921,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { goBack: operations.goBack, goForward: operations.goForward, refresh: operations.refresh, + stopLoading: operations.stopLoading, zoomIn: operations.zoomIn, zoomOut: operations.zoomOut, resetZoom: operations.resetZoom, diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 88a7fc467e425..42867b9d9cb44 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -39,7 +39,7 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, + POINTER_DOWN_HOST_CHANNEL, PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, RECORDING_POINTER_CHANNEL, @@ -47,6 +47,7 @@ import { RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui"; const INPUT_LAYER_ATTRIBUTE = "data-t3code-annotation-input"; @@ -193,6 +194,9 @@ const applyAnnotationTheme = ( const reportHumanPointerInput = (event: PointerEvent): void => { if (!event.isTrusted) return; + // The guest does not always take focus on a click, so the host's webview + // `focus` event can't be relied on to dismiss open menus and popovers. + ipcRenderer.sendToHost(POINTER_DOWN_HOST_CHANNEL); ipcRenderer.send(HUMAN_INPUT_CHANNEL, { kind: "pointer", x: event.clientX, @@ -245,34 +249,28 @@ const isolateOverlayKey = (event: KeyboardEvent): void => { for (const type of ["keydown", "keypress", "keyup"] as const) window.addEventListener(type, isolateOverlayKey, true); -const MOUSE_BUTTON_BACK = 3; -const MOUSE_BUTTON_FORWARD = 4; - -const navigationDirectionForButton = (button: number): "back" | "forward" | null => { - if (button === MOUSE_BUTTON_BACK) return "back"; - if (button === MOUSE_BUTTON_FORWARD) return "forward"; - return null; -}; - -// Chromium routes thumb-button navigation to the focused WebContents; navigate this hovered guest explicitly. -const suppressNavigationButton = (event: MouseEvent): void => { - if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return; - event.preventDefault(); - event.stopImmediatePropagation(); -}; - -const requestNavigationForButton = (event: MouseEvent): void => { - if (!event.isTrusted) return; - const direction = navigationDirectionForButton(event.button); - if (direction === null) return; - event.preventDefault(); - event.stopImmediatePropagation(); - ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction }); -}; - -window.addEventListener("mousedown", suppressNavigationButton, true); -window.addEventListener("mouseup", requestNavigationForButton, true); -window.addEventListener("auxclick", suppressNavigationButton, true); +let replayedThumbPress: { readonly x: number; readonly y: number } | null = null; +ipcRenderer.on( + THUMB_PRESS_CHANNEL, + (_event, phase: unknown, x: unknown, y: unknown, button: unknown) => { + if (phase !== "down" && phase !== "up") return; + if (typeof x !== "number" || typeof y !== "number" || typeof button !== "number") return; + // Main reports presses inside a frame in that frame's coordinates. + const inFrame = document.querySelector("iframe:hover, frame:hover, object:hover, embed:hover"); + if (phase === "up") { + const pressed = replayedThumbPress; + replayedThumbPress = null; + // A replayed press is always released, at its own point if the release lands in a frame. + if (pressed) recordingCursor?.press(inFrame ? pressed : { x, y }, "up"); + return; + } + if (inFrame) return; + replayedThumbPress = { x, y }; + ipcRenderer.sendToHost(POINTER_DOWN_HOST_CHANNEL); + ipcRenderer.send(HUMAN_INPUT_CHANNEL, { kind: "pointer", x, y, button }); + recordingCursor?.press({ x, y }, "down"); + }, +); const nextId = createAnnotationIdSource(); diff --git a/apps/desktop/src/preview/RecordingCursor.ts b/apps/desktop/src/preview/RecordingCursor.ts index 29f1865de291f..ab74c361b68e0 100644 --- a/apps/desktop/src/preview/RecordingCursor.ts +++ b/apps/desktop/src/preview/RecordingCursor.ts @@ -156,13 +156,15 @@ export function installRecordingCursor( moveHuman(point); pointer(point, "move"); }; + const press = (point: { readonly x: number; readonly y: number }, phase: "down" | "up") => { + if (phase === "down") moveHuman(point); + pointer(point, phase); + }; const pointerDown = (event: PointerEvent) => { - if (event.pointerType === "touch") return; - moveHuman({ x: event.clientX, y: event.clientY }); - pointer({ x: event.clientX, y: event.clientY }, "down"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "down"); }; const pointerUp = (event: PointerEvent) => { - if (event.pointerType !== "touch") pointer({ x: event.clientX, y: event.clientY }, "up"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "up"); }; const keyDown = (event: KeyboardEvent) => { if (event.isComposing || event.repeat) return; @@ -196,6 +198,7 @@ export function installRecordingCursor( window.addEventListener("blur", hide); return { move, + press, keyPress, setController, setTheme, diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 868e1c139fbdd..04406f63c6b3d 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -4,6 +4,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Tracer from "effect/Tracer"; @@ -160,6 +161,49 @@ describe("DesktopSettings", () => { ), ); + it.effect("keeps saved preferences when a read fails before a bounds save", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + yield* writeSettingsPatch({ serverExposureMode: "network-accessible" }); + const cause = PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "readFileString", + pathOrDescriptor: environment.desktopSettingsPath, + }); + let failRead = true; + const settings = yield* DesktopAppSettings.make.pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fileSystem, + readFileString: (path) => + Effect.suspend(() => { + if (failRead && path === environment.desktopSettingsPath) { + failRead = false; + return Effect.fail(cause); + } + return fileSystem.readFileString(path); + }), + }), + ), + ); + + yield* Effect.exit(settings.load); + yield* Effect.exit( + settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, false), + ); + + const persisted = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + assert.equal(persisted.serverExposureMode, "network-accessible"); + }), + ), + ); + it.effect("loads lenient persisted desktop settings JSON", () => withSettings( Effect.gen(function* () { @@ -196,6 +240,28 @@ describe("DesktopSettings", () => { ), ); + it.effect("keeps Local environment off when another value in the file is unreadable", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString( + environment.desktopSettingsPath, + `{ "localEnvironmentEnabled": false, "serverExposureMode": "tailnet" }\n`, + ); + + assert.isFalse((yield* settings.load).localEnvironmentEnabled); + yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false); + assert.include( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + `"localEnvironmentEnabled":false`, + ); + }), + ), + ); + it.effect("rejects window bounds that do not satisfy the domain schema", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 4c2ae8d1d1342..e81da70660648 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -13,6 +13,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as SynchronizedRef from "effect/SynchronizedRef"; @@ -88,20 +90,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({ height: Schema.Number, }); +// A value this build cannot read drops only its own key, so the rest of the file +// still loads and is written back instead of every setting resetting to defaults. +const optionalReadableKey = (schema: S) => + Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); + const DesktopSettingsDocument = Schema.Struct({ - localEnvironmentEnabled: Schema.optionalKey(Schema.Boolean), - linuxPasswordStore: Schema.optionalKey(Schema.Unknown), - mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)), - mainWindowMaximized: Schema.optionalKey(Schema.Boolean), - serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema), - tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean), - tailscaleServePort: Schema.optionalKey(Schema.Number), - updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema), - updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean), - wslBackendEnabled: Schema.optionalKey(Schema.Boolean), - wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])), - wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)), - wslOnly: Schema.optionalKey(Schema.Boolean), + localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), + linuxPasswordStore: optionalReadableKey(Schema.Unknown), + mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + mainWindowMaximized: optionalReadableKey(Schema.Boolean), + serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema), + tailscaleServeEnabled: optionalReadableKey(Schema.Boolean), + tailscaleServePort: optionalReadableKey(Schema.Number), + updateChannel: optionalReadableKey(DesktopUpdateChannelSchema), + updateChannelConfiguredByUser: optionalReadableKey(Schema.Boolean), + wslBackendEnabled: optionalReadableKey(Schema.Boolean), + wslMode: optionalReadableKey(Schema.Literals(["local", "wsl"])), + wslDistro: optionalReadableKey(Schema.NullOr(Schema.String)), + wslOnly: optionalReadableKey(Schema.Boolean), }); type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type; @@ -379,15 +386,20 @@ function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings { return setWslOnly(setWslBackendEnabled(settings, false), false); } +// Fails only when the file may exist but could not be read; a missing file means defaults. function readSettings( fileSystem: FileSystem.FileSystem, settingsPath: string, appVersion: string, -): Effect.Effect { +): Effect.Effect { const defaultSettings = resolveDefaultDesktopSettings(appVersion); return fileSystem.readFileString(settingsPath).pipe( - Effect.option, + Effect.asSome, + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed(Option.none()), + ), Effect.flatMap( Option.match({ onNone: () => Effect.succeed(defaultSettings), @@ -476,6 +488,8 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const random = yield* SecureRandom.SecureRandom; const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings); + // Writing over a settings file we could not read would erase the preferences it holds. + const persistenceEnabled = yield* Ref.make(true); const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) => SynchronizedRef.modify(settingsRef, (settings) => { @@ -492,17 +506,23 @@ export const make = Effect.gen(function* () { return Effect.succeed([settingsChange(settings, false), settings] as const); } - return random.uuidV4().pipe( - Effect.map((uuid) => uuid.replace(/-/g, "")), - Effect.flatMap((suffix) => - writeSettings({ - fileSystem, - path, - settingsPath: environment.desktopSettingsPath, - settings: nextSettings, - defaultSettings: environment.defaultDesktopSettings, - suffix, - }), + return Ref.get(persistenceEnabled).pipe( + Effect.flatMap((enabled) => + enabled + ? random.uuidV4().pipe( + Effect.map((uuid) => uuid.replace(/-/g, "")), + Effect.flatMap((suffix) => + writeSettings({ + fileSystem, + path, + settingsPath: environment.desktopSettingsPath, + settings: nextSettings, + defaultSettings: environment.defaultDesktopSettings, + suffix, + }), + ), + ) + : Effect.void, ), Effect.as([settingsChange(nextSettings, true), nextSettings] as const), ); @@ -515,6 +535,17 @@ export const make = Effect.gen(function* () { fileSystem, environment.desktopSettingsPath, environment.appVersion, + ).pipe( + Effect.catch((cause) => + Effect.logWarning( + "Could not read desktop settings; using defaults without saving changes.", + cause, + ).pipe( + Effect.annotateLogs({ settingsPath: environment.desktopSettingsPath }), + Effect.andThen(Ref.set(persistenceEnabled, false)), + Effect.as(resolveDefaultDesktopSettings(environment.appVersion)), + ), + ), ); return yield* SynchronizedRef.setAndGet(settingsRef, settings); }).pipe(Effect.withSpan("desktop.settings.load")), diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 1ab9b3159e1f9..90c8740f83725 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -110,7 +110,7 @@ const withClientSettings = ( prefix: "t3-desktop-client-settings-test-", }); return yield* effect.pipe(Effect.provide(layer(baseDir))); - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); describe("DesktopClientSettings", () => { it.effect("saves through a symlinked client settings file without replacing the link", () => diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts index 0001548f4534f..7be39dbe1562d 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts @@ -150,7 +150,7 @@ const withSavedEnvironments = ( prefix: "t3-desktop-saved-environments-test-", }); return yield* effect.pipe(Effect.provide(layer(baseDir, options))); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopSavedEnvironments", () => { it.effect("loads lenient saved environment registry documents", () => diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts index 1e5b6dafc6cae..15977b34f398b 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts @@ -144,7 +144,7 @@ describe("DesktopSshPasswordPrompts", () => { yield* prompts.resolve({ requestId: request.requestId, password: "secret" }); assert.equal(yield* Fiber.join(fiber), "secret"); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); + }).pipe(Effect.provide(layer(testWindow.window))); }); it.effect.each(["answered", "cancelled", "timed out", "interrupted"] as const)( @@ -189,7 +189,7 @@ describe("DesktopSshPasswordPrompts", () => { .map((message) => message.args), [[request.requestId]], ); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); + }).pipe(Effect.provide(layer(testWindow.window))); }, ); @@ -219,6 +219,6 @@ describe("DesktopSshPasswordPrompts", () => { assert.equal(password, "secret"); assert.equal(testWindow.isFocused(), false); assert.equal(testWindow.closedListenerCount(), 0); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); + }).pipe(Effect.provide(layer(testWindow.window))); }); }); diff --git a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts b/apps/desktop/src/wsl/DesktopWslServerTree.test.ts index 7eaf362a326aa..34dcbea08a0ee 100644 --- a/apps/desktop/src/wsl/DesktopWslServerTree.test.ts +++ b/apps/desktop/src/wsl/DesktopWslServerTree.test.ts @@ -6,7 +6,6 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -42,20 +41,14 @@ const layerEnvironment = (input: { ), ); -const withTempDir = ( - run: (tempDir: string) => Effect.Effect, -): Effect.Effect< - A, - E | PlatformError.PlatformError, - FileSystem.FileSystem | Exclude -> => +const withTempDir = (run: (tempDir: string) => Effect.Effect) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-wsl-server-tree-test-", }); return yield* run(tempDir); - }).pipe(Effect.scoped); + }); const ensureWith = (input: { readonly baseDir: string; diff --git a/apps/desktop/src/wsl/wslPathParsing.test.ts b/apps/desktop/src/wsl/wslPathParsing.test.ts index 0a814229665dd..ed491f58381ae 100644 --- a/apps/desktop/src/wsl/wslPathParsing.test.ts +++ b/apps/desktop/src/wsl/wslPathParsing.test.ts @@ -77,8 +77,15 @@ describe("wslUncPathToLinuxPath", () => { expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/"); }); + it("maps UNC paths of distros whose names start or end with a dot or hyphen", () => { + for (const name of ["Ubuntu-", "Ubuntu.", ".Ubuntu", "-Ubuntu"]) { + expect(wslUncPathToLinuxPath(`\\\\wsl.localhost\\${name}\\home\\josh`)).toBe("/home/josh"); + } + }); + it("rejects invalid distro names and non-WSL paths", () => { expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull(); + expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\..\\home")).toBeNull(); expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull(); }); }); @@ -107,9 +114,13 @@ describe("resolveWslPickFolderDefaultPath", () => { }); describe("isValidDistroName", () => { - it("rejects names with trailing whitespace, hyphen, or dot", () => { - for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) { - expect(isValidDistroName(name)).toBe(false); + it("rejects names with trailing whitespace", () => { + expect(isValidDistroName("Ubuntu ")).toBe(false); + }); + + it("accepts names WSL registers with a leading or trailing dot or hyphen", () => { + for (const name of ["Ubuntu-", "Ubuntu.", ".Ubuntu", "-Ubuntu"]) { + expect(isValidDistroName(name)).toBe(true); } }); diff --git a/apps/desktop/src/wsl/wslPathParsing.ts b/apps/desktop/src/wsl/wslPathParsing.ts index a1ce99c129d13..1df64f91dac0e 100644 --- a/apps/desktop/src/wsl/wslPathParsing.ts +++ b/apps/desktop/src/wsl/wslPathParsing.ts @@ -9,7 +9,8 @@ export interface WslConfig { } // Literal spaces only; \s would accept controls and corrupt UNC distro paths. -const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/; +// "." and ".." would be path segments in a UNC path, not distro names. +const DISTRO_NAME_PATTERN = /^(?!\.{1,2}$)[\w.-](?:[\w .-]*[\w.-])?$/; export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] { const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe; diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 0f4e70b20cc3c..924fa4ddeb14a 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -19,6 +19,7 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + private var indicatorObservations: [NSKeyValueObservation] = [] required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -136,12 +137,29 @@ final class T3ScrollEdgeBleedView: ExpoView { containerClipped = containerClipped ?? true container.layer.masksToBounds = false } + applyIndicatorInset() + // React Native rewrites every indicator inset when its `scrollIndicatorInsets` prop changes, + // which the keyboard-aware list animates while a reply streams; put the inset back at once. + if bleeding, indicatorObservations.isEmpty { + let keyPaths = [\UIScrollView.verticalScrollIndicatorInsets, \.scrollIndicatorInsets] + indicatorObservations = keyPaths.map { + scrollView.observe($0) { [weak self] _, _ in + MainActor.assumeIsolated { self?.applyIndicatorInset() } + } + } + } else if !bleeding { + indicatorObservations = [] + } + applied = bleeding + } + + private func applyIndicatorInset() { + guard let scrollView else { return } var indicators = scrollView.verticalScrollIndicatorInsets if indicators.right != bleed.right { indicators.right = bleed.right scrollView.verticalScrollIndicatorInsets = indicators } - applied = bleeding } private func detach() { diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt index e5c8f6c0fd8f4..c41d2d545ca61 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt @@ -67,6 +67,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex private var streamedOutput: TerminalOutputBuffer? = null private var cols = 0 private var rows = 0 + private var cellSize = 0 to 0 private var measuredCols = 0 private var measuredRows = 0 private var clearingInput = false @@ -356,25 +357,24 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex applyGrid() } + @Suppress("ComplexCondition") private fun applyGrid() { if (measuredCols <= 0 || measuredRows <= 0 || isCleanedUp) return val shared = sharedGrid.takeIf { it.size == 2 && it[0] > 0 && it[1] > 0 } val nextCols = shared?.get(0)?.coerceAtMost(measuredCols) ?: measuredCols val nextRows = shared?.get(1)?.coerceAtMost(measuredRows) ?: measuredRows - if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return + val nextCellSize = terminalCanvas.cellWidthPx.toInt() to terminalCanvas.cellHeightPx.toInt() + if (nextCols == cols && nextRows == rows && nextCellSize == cellSize && terminalHandle != 0L) { + return + } cols = nextCols rows = nextRows + cellSize = nextCellSize val response = if (terminalHandle == 0L) { createTerminal() ByteArray(0) } else { - GhosttyBridge.nativeResize( - terminalHandle, - cols, - rows, - terminalCanvas.cellWidthPx.toInt(), - terminalCanvas.cellHeightPx.toInt(), - ) + GhosttyBridge.nativeResize(terminalHandle, cols, rows, cellSize.first, cellSize.second) } emitResponse(response) if (!hasPendingBuffer) feedPendingBuffer() @@ -387,8 +387,8 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex terminalHandle = GhosttyBridge.nativeCreate( cols, rows, - terminalCanvas.cellWidthPx.toInt(), - terminalCanvas.cellHeightPx.toInt(), + cellSize.first, + cellSize.second, foregroundColorValue, backgroundColorValue, cursorColorValue, diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift index d8f0b29ebce52..1ed02e6a16cbf 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -285,7 +285,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != fontSize else { return } inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) - resetSurface() + applyConfigInPlace() } } @@ -321,14 +321,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != appearanceScheme else { return } appearance = TerminalAppearanceScheme(value: appearanceScheme) - resetSurface() + applyConfigInPlace() } } var themeConfig: String = "" { didSet { guard oldValue != themeConfig else { return } - resetSurface() + applyConfigInPlace() } } @@ -663,7 +663,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte surfaceCreationFailed = true return } - loadThemeConfig(into: config) + // Creation proceeds without the file, as before; font_size is also set on the surface config. + _ = loadThemeConfig(into: config) ghostty_config_finalize(config) defer { ghostty_config_free(config) } @@ -710,6 +711,27 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte setNeedsLayout() } + // Font and theme change in place: a new surface would replay output and re-answer its queries. + private func applyConfigInPlace() { + guard let app, let surface else { + resetSurface() + return + } + guard let config = ghostty_config_new() else { return } + defer { ghostty_config_free(config) } + let loaded = loadThemeConfig(into: config) + ghostty_config_finalize(config) + ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme) + ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme) + tickApp() + // Without the file, the config lacks font-size and would reset the surface to defaults. + if loaded { + ghostty_surface_update_config(surface, config) + } + resizeSurface() + setNeedsLayout() + } + private func destroySurface() { // Unblock the io thread before ghostty_surface_free joins it. tickApp() @@ -933,16 +955,16 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte terminalViewport.backgroundColor = backgroundColorValue } - private func loadThemeConfig(into config: ghostty_config_t) { - guard let path = writeThemeConfigFile() else { return } + private func loadThemeConfig(into config: ghostty_config_t) -> Bool { + guard let path = writeThemeConfigFile() else { return false } path.withCString { cString in ghostty_config_load_file(config, cString) } + return true } private func writeThemeConfigFile() -> String? { - guard !themeConfig.isEmpty else { return nil } - let configContents = themeConfig + let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n" let url = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index fc4dfdf3a417a..b92c0ca9d42c5 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -83,7 +83,10 @@ import { splashCanHide, useLaunchSplashHomeRowsPending, } from "./features/home/home-launch-splash"; -import { restoreSettingsLinkState } from "./features/settings/settings-navigation"; +import { + restoreSettingsLinkState, + settingsLinkAction, +} from "./features/settings/settings-navigation"; import { hydrateWorkspaceSelections, launchWorkspaceURL, @@ -143,14 +146,16 @@ const appLinking = { getActionFromState: ( state: Parameters[0], options: Parameters[1], - ): ReturnType => - // Our router handles the selection; React Navigation's type only lists its own actions. - (workspaceDetailLinkAction(state) as ReturnType) ?? - pairingFormLinkAction( - state, - rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined, - ) ?? - getActionFromState(state, options), + ): ReturnType => { + const current = rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined; + return ( + // Our router handles the selection; React Navigation's type only lists its own actions. + (workspaceDetailLinkAction(state) as ReturnType) ?? + pairingFormLinkAction(state, current) ?? + settingsLinkAction(state, current) ?? + getActionFromState(state, options) + ); + }, getStateFromPath: getAppStateFromPath, }; diff --git a/apps/mobile/src/components/ui/AppBar.tsx b/apps/mobile/src/components/ui/AppBar.tsx index 7f76d91066130..b691faa300dae 100644 --- a/apps/mobile/src/components/ui/AppBar.tsx +++ b/apps/mobile/src/components/ui/AppBar.tsx @@ -1,8 +1,8 @@ import { Toolbar } from "./Toolbar"; import { AppActivityIndicator } from "./AppActivityIndicator"; -import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens"; -import { NavigationContext } from "@react-navigation/native"; -import { use, useId, useLayoutEffect } from "react"; +import type { HeaderBarButtonMailSearchToolbarItem, SearchBarCommands } from "react-native-screens"; +import { NavigationContext, NavigationRouteContext } from "@react-navigation/native"; +import { use, useId, useLayoutEffect, useRef, useSyncExternalStore } from "react"; import { View } from "react-native"; import { createNativeHeaderMenu } from "./nativeHeaderMenu.ios"; import { ScreenHeaderButton } from "./ScreenHeaderButton"; @@ -63,6 +63,17 @@ export function AppBar(props: AppBarProps) { ? { ...props.backInSplitView, onPress: splitBackPress } : null; const navigation = use(NavigationContext); + const route = use(NavigationRouteContext); + // A thread opened from another thread sits on it, not beside the list, so it keeps Back. + const threadBelow = useSyncExternalStore( + (onChange) => navigation?.addListener("state", onChange) ?? (() => {}), + () => { + const routes = navigation?.getState()?.routes; + const index = routes?.findIndex((candidate) => candidate.key === route?.key) ?? -1; + return route?.name === "Thread" && index > 0 && routes?.[index - 1]?.name === "Thread"; + }, + ); + const listBeside = layout.usesSplitView && props.onBackToList !== undefined && !threadBelow; const rootBack = !layout.usesSplitView && props.onBackToList && navigation?.canGoBack() === false ? props.onBackToList @@ -78,6 +89,19 @@ export function AppBar(props: AppBarProps) { const usesNativeMailSearchToolbar = useNativeMailSearchToolbar(); const { search, menus } = props; const menu = menus?.[0]; + const searchBarRef = useRef(null); + const nativeSearchText = useRef(search?.value ?? ""); + const searchValue = search?.value; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the native search bar keeps its own text; a value the caller changes (a reset) has to be pushed into it + useLayoutEffect(() => { + if (searchValue === undefined || searchValue === nativeSearchText.current) return; + nativeSearchText.current = searchValue; + searchBarRef.current?.setText(searchValue); + }, [searchValue]); + const reportSearchText = (text: string) => { + nativeSearchText.current = text; + search?.onChangeText(text); + }; const compactSearch = search !== undefined && (search.compactToolbar ?? !layout.usesSplitView) && @@ -100,7 +124,7 @@ export function AppBar(props: AppBarProps) { headerBackVisible: props.onClose === undefined && splitBack === null && - !(layout.usesSplitView && props.onBackToList) && + !listBeside && !(props.guardBack && props.onBack), ...(props.guardBack ? { gestureEnabled: false } : undefined), title: props.title, @@ -142,8 +166,9 @@ export function AppBar(props: AppBarProps) { ? { obscureBackground: false } : undefined), placeholder: search.placeholder, - onChangeText: (event) => search.onChangeText(event.nativeEvent.text), - onCancelButtonPress: () => search.onChangeText(""), + ref: searchBarRef, + onChangeText: (event) => reportSearchText(event.nativeEvent.text), + onCancelButtonPress: () => reportSearchText(""), }, } : undefined), diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index e9a24552ce369..1205c746e9fa1 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -24,6 +24,7 @@ import * as Fiber from "effect/Fiber"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as MobileDatabase from "../persistence/mobile-database"; import { make } from "./environment-cache-store"; @@ -567,7 +568,7 @@ describe("mobile SQLite environment cache store", () => { }), ); - it.live("returns cached threads before their pull request links, which load after", () => + it.effect("returns cached threads before their pull request links, which load after", () => Effect.gen(function* () { const memory = makeDatabase(); const store = yield* make().pipe( @@ -592,12 +593,13 @@ describe("mobile SQLite environment cache store", () => { const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID)); expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]); - const links = yield* shell.loadPullRequests!; - expect([...links]).toEqual([[THREAD_ID, [link]]]); + const links = yield* Effect.forkChild(shell.loadPullRequests!); + yield* TestClock.adjust("1 millis"); + expect([...(yield* Fiber.join(links))]).toEqual([[THREAD_ID, [link]]]); }), ); - it.live("keeps cached threads when their pull request links cannot be read", () => { + it.effect("keeps cached threads when their pull request links cannot be read", () => { const messages: Array = []; const logger = Logger.make(({ message }) => { messages.push(message); @@ -633,7 +635,9 @@ describe("mobile SQLite environment cache store", () => { const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID)); expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]); - expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]); + const links = yield* Effect.forkChild(shell.loadPullRequests!); + yield* TestClock.adjust("1 millis"); + expect([...(yield* Fiber.join(links))]).toEqual([[readable.id, [link]]]); expect(messages).toHaveLength(1); expect(memory.removed).toEqual([]); }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); diff --git a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx index 3fae93f483bcc..d4a4690dbaf4b 100644 --- a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx +++ b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx @@ -405,7 +405,7 @@ function PreviewStreamDocumentView({ onPictureInPicture?.(message, message.detail); return; case "status": - clearBootstrapTimer(); + if (message.status !== "connecting") clearBootstrapTimer(); if (message.status === "error") { fail(message.detail ?? "Browser stream failed."); return; diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index 0c40fc4e088b4..b962d716b992a 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -63,6 +63,7 @@ function DocumentWebPreview(props: { readonly uri: string }) { originWhitelist={["*"]} allowsBackForwardNavigationGestures allowsFullscreenVideo + allowsInlineMediaPlayback setSupportMultipleWindows={false} onShouldStartLoadWithRequest={(request) => { if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) { diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx new file mode 100644 index 0000000000000..21f64998a3be9 --- /dev/null +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.test.tsx @@ -0,0 +1,79 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const queries = vi.hoisted(() => [] as { cwd: string | null; searchQuery: string }[]); + +vi.mock("@t3tools/client-runtime/state/filesystem", () => ({ + resolveFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false }), +})); +vi.mock("../../state/session", () => ({ environmentSession: { sessionStateAtom: () => null } })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null, error: null }) })); +vi.mock("../../state/presentation", () => ({ + useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ themeAppearance: "dark" }), +})); +vi.mock("./preload-workspace-file", () => ({ preloadWorkspaceFileContents: () => {} })); +vi.mock("./FileTreeBrowser", () => ({ FileTreeBrowser: () => null })); +vi.mock("./useFileTreeEntries", () => ({ + useFileTreeEntries: (input: { cwd: string | null; searchQuery: string }) => { + queries.push({ cwd: input.cwd, searchQuery: input.searchQuery }); + return { refresh: () => {}, selectPath: () => {} }; + }, +})); +vi.mock("../../components/ui/SheetPane", () => ({ + SheetPane: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../components/ui/AppBar", () => ({ + AppBar: (props: { search: { value: string; onChangeText: (value: string) => void } }) => ( + props.search.onChangeText(event.target.value)} + /> + ), +})); + +import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane"; + +it("starts unfiltered when the mounted pane switches to another workspace", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + const render = (cwd: string) => + act(() => + root.render( + {}} + />, + ), + ); + try { + render("/first"); + const input = container.querySelector("input")!; + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + "alpha", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(queries.at(-1)).toEqual({ cwd: "/first", searchQuery: "alpha" }); + + render("/second"); + expect(queries.at(-1)).toEqual({ cwd: "/second", searchQuery: "" }); + expect(container.querySelector("input")!.value).toBe(""); + } finally { + act(() => root.unmount()); + container.remove(); + } +}); diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index 26cafcc764950..cc0c86e6d3e4b 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -20,7 +20,11 @@ export function ThreadFileNavigatorPane(props: { readonly selectedPath: string | null; readonly onSelectFile: (path: string) => void; }) { - const [searchQuery, setSearchQuery] = useState(""); + const workspaceKey = JSON.stringify([props.environmentId, props.cwd]); + // The pane stays mounted across thread switches; a query only filters the workspace it was typed in. + const [search, setSearch] = useState({ workspaceKey, query: "" }); + const searchQuery = search.workspaceKey === workspaceKey ? search.query : ""; + const setSearchQuery = (query: string) => setSearch({ workspaceKey, query }); const { themeAppearance: highlightTheme } = useAppearancePreferences(); const fileAccessSession = useEnvironmentQuery( environmentSession.sessionStateAtom(props.environmentId), @@ -48,7 +52,7 @@ export function ThreadFileNavigatorPane(props: { }; const fileTree = ( + buildHomeProjectScopes({ + projects, + environmentId: selectedEnvironmentId, + projectGroupingMode: listOptions.projectGroupingMode, + }), + [listOptions.projectGroupingMode, projects, selectedEnvironmentId], ); const projectFilterOptions = useMemo( () => - pickableProjectGroups( - buildHomeProjectScopes({ - projects, - environmentId: selectedEnvironmentId, - projectGroupingMode: listOptions.projectGroupingMode, - }), - ).map((scope) => ({ + pickableProjectGroups(projectScopes).map((scope) => ({ key: scope.key, label: scope.title, })), - [listOptions.projectGroupingMode, projects, selectedEnvironmentId], + [projectScopes], ); - const selectedProjectKey = projectFilterOptions.some( - (project) => project.key === resolvedProjectKey, - ) - ? resolvedProjectKey - : null; + const selectedProjectKey = + resolveHomeProjectFilterScope(projectScopes, projects, listOptions)?.key ?? null; if (layout.usesSplitView && !nativePrimaryColumn) { return ( diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 1b2e1a8c541f7..7c0392497645b 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -1,4 +1,8 @@ -import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; +import { + buildProjectGroups, + pickableProjectGroups, + resolveScratchProjectScopeKey, +} from "@t3tools/client-runtime/state/project-grouping"; import type { EnvironmentProject, EnvironmentThreadShell, @@ -70,6 +74,24 @@ export function buildHomeProjectScopes(input: { }); } +/** The scope the thread list's project filter shows; an archived or unknown key shows all projects. */ +export function resolveHomeProjectFilterScope( + scopes: ReadonlyArray, + projects: ReadonlyArray, + options: { + readonly selectedProjectKey: string | null; + readonly projectGroupingMode: SidebarProjectGroupingMode; + }, +): HomeProjectScope | null { + // A legacy per-environment scratch key resolves here; the stored value is only + // rewritten when the user picks a filter. + const key = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { + sidebarProjectGroupingMode: options.projectGroupingMode, + sidebarProjectGroupingOverrides: {}, + }); + return pickableProjectGroups(scopes).find((scope) => scope.key === key) ?? null; +} + export function findHomeProjectScope( scopes: ReadonlyArray, key: string | null, diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 3a32e33523611..a90ba87eedda2 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -59,6 +59,8 @@ import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; +import { savedConnectionsByIdAtom } from "../../state/use-remote-environment-registry"; +import { workspaceConnections } from "../../state/workspace"; import { DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS, resolveMobileProjectGroupingSettings, @@ -83,7 +85,8 @@ import { import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; import { HomeListOptionsProvider } from "../home/home-list-options"; -import { newTaskDestination } from "../threads/new-task-project-selection"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; +import { newTaskDestination, newTaskFilteredProject } from "../threads/new-task-project-selection"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; import { PaneContext } from "../../components/ui/Pane"; import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; @@ -606,12 +609,38 @@ function AdaptiveWorkspaceLayoutContent( : undefined; const preferences = appAtomRegistry.get(mobilePreferencesAtom); const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined; + // Resolve the thread list's filter as useHomeListOptions does: a removed connection's filter reads as all. + const listFilters = saved?.threadListFilters; + const listEnvironmentId = + listFilters?.environmentId != null && + appAtomRegistry.get(savedConnectionsByIdAtom)[listFilters.environmentId] !== undefined + ? listFilters.environmentId + : null; + const filteredScope = resolveHomeProjectFilterScope( + buildHomeProjectScopes({ projects, environmentId: listEnvironmentId, projectGroupingMode }), + projects, + { selectedProjectKey: listFilters?.projectKey ?? null, projectGroupingMode }, + ); + const connectedEnvironmentIds = new Set( + appAtomRegistry + .get(workspaceConnections.environmentsAtom) + .filter((environment) => environment.connectionState === "connected") + .map((environment) => environment.environmentId), + ); handleSelectThreadRoute( newTaskDestination({ projects, requestId: uuidv4(), useLastProject: saved?.useLastProjectForNewThreads, currentProject: environmentId && projectId ? { environmentId, projectId } : undefined, + filteredProject: filteredScope + ? newTaskFilteredProject( + filteredScope, + listEnvironmentId, + connectedEnvironmentIds, + saved?.lastThreadProject, + ) + : undefined, lastProject: saved?.lastThreadProject, }), ); diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx index a03a36bc94762..75d139621562a 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx @@ -24,6 +24,8 @@ import { WorkspaceAppBarScope } from "../../../components/ui/WorkspaceAppBar.and import { usePaneRole } from "../../../components/ui/Pane"; import { AndroidWorkspaceSidebar } from "./AndroidWorkspaceSidebar.android"; import type { WorkspaceTab } from "./workspace-tabs-state"; +import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab"; +import { useHardwareBack } from "../../../lib/backHandler"; const TABS: readonly WorkspaceTab[] = NAVIGATION_TAB_ORDER; @@ -49,6 +51,18 @@ function WorkspaceRoot() { : 16, }; const tab = workspace.state.selectedTab; + const selectTab = useSelectWorkspaceTab(); + // Tabs are panes of Home, not routes, so Back has nothing to pop and would leave the app. + // An open search keeps Back for itself. + useHardwareBack( + tab !== "threads" && + enabled.includes("threads") && + workspace.state.tabs[tab].searchMode === "resting", + () => { + selectTab("threads"); + return true; + }, + ); return ( diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts index 3f217fd70c8bc..3cd3fe6d0978f 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts @@ -1,6 +1,7 @@ +import * as NodeModule from "node:module"; import { describe, expect, it } from "vite-plus/test"; -import { restoreSettingsLinkState } from "../../settings/settings-navigation"; +import { restoreSettingsLinkState, settingsLinkAction } from "../../settings/settings-navigation"; import { workspaceSelectionsIn, workspaceTabColumns, @@ -19,6 +20,17 @@ const pullRequest = { params: { environmentId: "env", projectId: "project", repository: "o/r", number: 7 }, }; const settings = { key: "settings", name: "Settings" }; +const requireFromNative = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), +); +const { getStateFromPath } = requireFromNative("@react-navigation/core") as { + readonly getStateFromPath: typeof import("@react-navigation/native").getStateFromPath; +}; +const { StackRouter } = NodeModule.createRequire( + requireFromNative.resolve("@react-navigation/core/package.json"), +)("@react-navigation/routers") as { + readonly StackRouter: typeof import("@react-navigation/native").StackRouter; +}; const available = { thread: () => true, pullRequest: () => true }; const names = (state: { routes: readonly { name: string }[] }) => state.routes.map((route) => route.name); @@ -218,6 +230,31 @@ describe("Settings links", () => { expect(restoreSettingsLinkState(bare, undefined)).toBe(bare); }); + it("opens a link sent to the running app on the Settings tab, as its button does", () => { + const screens = { + Home: "", + Settings: "settings", + SettingsAbout: "settings/about", + SettingsAppearance: "settings/appearance", + }; + const router = StackRouter({}); + const options = { routeNames: Object.keys(screens), routeParamList: {}, routeGetIdList: {} }; + const open = router.getRehydratedState( + { index: 2, routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsAbout" }] }, + options, + ); + const follow = (path: string) => { + const link = getStateFromPath(path, { initialRouteName: "Home", screens })!; + const action = settingsLinkAction(link, open)!; + return router.getStateForAction(open, action, options)!; + }; + + expect(names(follow("settings"))).toEqual(["Home", "Settings"]); + const appearance = follow("settings/appearance"); + expect(names(appearance)).toEqual(["Home", "Settings", "SettingsAppearance"]); + expect(appearance.routes[1]!.key).toBe(open.routes[1]!.key); + }); + it("opens the sign-in link as a modal over the workspace", () => { const state = { routes: [{ name: "Home" }, { name: "SettingsAuth" }] }; expect(restoreSettingsLinkState(state, "SettingsAppearance")).toBe(state); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts index f1c839630eb34..797da115a20eb 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts @@ -11,6 +11,8 @@ import { workspaceSearchBottomClearance, workspaceDockBottomClearance, workspaceUsesColumns, + type WorkspaceTab, + type WorkspaceTabsState, } from "./workspace-tabs-state"; describe("compact list clearance", () => { @@ -179,12 +181,25 @@ describe("workspace root navigation", () => { }); }); -const mocks = vi.hoisted(() => ({ split: false, floating: false })); +const mocks = vi.hoisted(() => ({ + split: false, + floating: false, + state: undefined as WorkspaceTabsState | undefined, + openWorkspaceTab: (_tab: string) => {}, + backListeners: new Set<() => boolean>(), +})); vi.mock("../../settings/appearance/AppearancePreferencesProvider", () => ({ useAndroidFloatingTabs: () => mocks.floating, })); vi.mock("react-native", () => ({ + BackHandler: { + addEventListener: (_event: string, listener: () => boolean) => { + mocks.backListeners.add(listener); + return { remove: () => mocks.backListeners.delete(listener) }; + }, + }, + Keyboard: { dismiss: () => undefined }, useWindowDimensions: () => ({ width: 400, height: 800 }), View: ({ children }: { children: ReactNode }) => createElement("div", null, children), })); @@ -198,12 +213,16 @@ vi.mock("../AdaptiveWorkspaceLayout", () => ({ startNewTask: () => undefined, }), })); +vi.mock("@react-navigation/native", () => ({ useIsFocused: () => true })); +vi.mock("../adaptive-workspace-context", () => ({ + useAdaptiveWorkspaceLayout: () => ({ openWorkspaceTab: mocks.openWorkspaceTab }), +})); vi.mock("./navigation-tabs", () => ({ useEnabledNavigationTabs: () => ["threads", "pullRequests", "usage"], })); vi.mock("./WorkspaceTabsContext", () => ({ WorkspaceTabsContext: createContext(null), - useWorkspaceTabs: () => ({ state: { selectedTab: "usage" } }), + useWorkspaceTabs: () => ({ state: mocks.state, dispatch: () => undefined }), })); vi.mock("./WorkspaceExtraTab", () => ({ WorkspaceExtraTab: function UsageProbe() { @@ -238,13 +257,37 @@ vi.mock("../../../components/ui/WorkspaceAppBar.android", () => ({ WorkspaceAppBarScope: ({ children }: { children: ReactNode }) => children, })); -function setup(split: boolean, floating: boolean) { +function setup(split: boolean, floating: boolean, state = selected("usage")) { mocks.split = split; mocks.floating = floating; + mocks.state = state; + mocks.openWorkspaceTab = () => undefined; + mocks.backListeners.clear(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); return { [Symbol.dispose]: () => vi.unstubAllGlobals() }; } +function selected(tab: WorkspaceTab) { + return workspaceTabsReducer(initialWorkspaceTabsState(), { type: "select", tab }); +} + +/** Android calls the newest listener first and stops at the first that handles Back. */ +function pressBack() { + return [...mocks.backListeners].reverse().some((listener) => listener()); +} + +it("Back from the Pulls tab returns to Threads instead of leaving the app", async () => { + using _actEnvironment = setup(false, false, selected("pullRequests")); + const opened: string[] = []; + mocks.openWorkspaceTab = (tab) => opened.push(tab); + const root = createRoot(document.createElement("div")); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + await act(async () => root.render(createElement(WorkspaceRootScreen))); + + expect(pressBack()).toBe(true); + expect(opened).toEqual(["threads"]); +}); + it.each([ [false, false], [true, false], diff --git a/apps/mobile/src/features/projects/AddProjectScreen.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.test.ts index ab331d0149e15..4718133f7a5a5 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.test.ts @@ -6,7 +6,11 @@ import * as NodeModule from "node:module"; import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { workspaceDetailRouter } from "../layout/workspace/workspace-detail-selection"; import type { NavigationState } from "@react-navigation/native"; -import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { act, createElement, isValidElement, type ReactNode } from "react"; @@ -22,7 +26,9 @@ const state = vi.hoisted(() => ({ id: string; title: string; workspaceRoot: string; + repositoryIdentity?: { canonicalKey: string }; }[], + cloneDestinations: [] as string[], createResult: null as Promise | null, createNewResult: null as Promise | null, startCloneResult: null as Promise | null, @@ -134,7 +140,15 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} })); +// Only filesystem.browse of `~` answers, with the host's home as its parentPath. +vi.mock("../../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: + () => + async ({ input }: { input?: { partialPath?: string } }) => + input?.partialPath === "~" + ? AsyncResult.success({ parentPath: "/home/tester", entries: [] }) + : undefined, +})); vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) })); vi.mock("../../state/presentation", () => ({ useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), @@ -144,6 +158,7 @@ vi.mock("../../state/sourceControl", () => ({ sourceControlEnvironment: { discovery: (input: unknown) => input, startProjectClone: async ({ input }: { input: { destinationPath: string } }) => { + state.cloneDestinations.push(input.destinationPath); if (state.startCloneResult) return state.startCloneResult; NodeFS.mkdirSync(input.destinationPath); return AsyncResult.success(undefined); @@ -230,7 +245,7 @@ function cloneAction() { renderScreen(() => AddProjectDestinationScreen({ environmentId: "environment", - remoteUrl: "https://example.com/repo.git", + remoteUrl: "https://example.com/owner/repo.git", repositoryName: "repo", }), ), @@ -274,6 +289,38 @@ describe("clone project permissions", () => { expect(state.projects).toEqual([]); }, ); + + it.each([ + [ + "opens the existing project of that repository instead of cloning into its folder", + "example.com/owner/repo", + false, + ], + ["leaves a folder holding another repository to the clone", "example.com/owner/other", true], + ])("%s", async (_name, canonicalKey, clones) => { + state.scopes.add(AuthOrchestrationOperateScope); + state.cloneDestinations = []; + state.startCloneResult = Promise.resolve( + AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))), + ); + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "repo", + workspaceRoot: NodePath.join(state.baseDirectory, "repo"), + repositoryIdentity: { canonicalKey }, + }, + ]; + try { + await cloneAction()(); + + expect(state.cloneDestinations.length > 0).toBe(clones); + } finally { + state.existingProjects = []; + state.startCloneResult = null; + } + }); }); function mountProjectFlow( @@ -488,10 +535,10 @@ describe("add project source environment", () => { }); describe("local project navigation", () => { - function setup() { + function setup(baseDirectory = "/tmp/t3-mobile-audit-fixture") { state.navigationState = undefined; state.scopes = new Set([AuthOrchestrationOperateScope]); - state.baseDirectory = "/tmp/t3-mobile-audit-fixture"; + state.baseDirectory = baseDirectory; state.projects = []; state.dispatch.mockReset(); state.alert.mockReset(); @@ -523,6 +570,28 @@ describe("local project navigation", () => { ); }); + it("opens an existing project typed as a home-relative path instead of creating it", async () => { + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "bike-documents", + workspaceRoot: "/home/tester/projects/bike-documents", + }, + ]; + try { + const { created, projected, submit } = setup("~/projects/bike-documents/"); + state.scopes.add(AuthFilesystemReadScope); + created.resolve(AsyncResult.success(undefined)); + projected.resolve(null); + await submit(); + + expect(state.projects).toEqual([]); + } finally { + state.existingProjects = []; + } + }); + it("does not replace a reopened flow when the previous submission finishes", async () => { const { created, projected, submit } = setup(); const navigation = mountProjectFlow(false); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 33b7de17c3914..56518cd071eac 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -387,7 +387,26 @@ function useBrowsePathInput( [browseNavigation], ); - return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath }; + // Registered roots are absolute and `~` expands on the host, so ask the host for its home. + const resolveHomePath = async (path: string): Promise => { + if ( + !/^~(?:[\\/]|$)/.test(path) || + !environment || + !readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) || + !canPreloadBrowsePath(environmentRuntime?.connectionState) + ) { + return path; + } + const home = await loadBrowsePath({ + environmentId: environment.environmentId, + input: { partialPath: "~" }, + }); + return AsyncResult.isSuccess(home) && home.value + ? `${home.value.parentPath.replace(/[\\/]+$/, "")}${path.slice(1)}` + : path; + }; + + return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath, resolveHomePath }; } function useEnvironmentOptions( @@ -730,16 +749,76 @@ async function draftWithPrompt( return draftId; } -function useCreateProject(environment: EnvironmentOption | null) { +function useOpenExistingProject(environment: EnvironmentOption | null) { const openNewTaskDraft = useOpenNewTaskDraft(); - const navigation = useNavigation(); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useAtomCommand(projectEnvironment.update, { label: "project unarchive", }); const projects = useProjects(); - return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => { + return async ( + path: string, + originRoute: ReturnType, + clone?: { readonly remoteUrl: string; readonly prompt: string | null }, + ): Promise => { + if (!environment) return false; + const existing = findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path, + }); + if (!existing) return false; + // A folder holding another repository is not this clone; let the clone report it occupied. + if ( + clone && + existing.repositoryIdentity?.canonicalKey !== + sourceControlClients.repositoryKeyFromRemote(clone.remoteUrl) + ) { + return false; + } + const prompt = clone?.prompt; + // Adding an archived project's folder again brings the project back. + const unarchived = + existing.archivedAt == null || + ( + await updateProject({ + environmentId: existing.environmentId, + input: { projectId: existing.id, archived: false }, + }) + )._tag === "Success"; + Dialog.alert( + "Project already exists", + unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, + ); + openNewTaskDraft( + { + environmentId: existing.environmentId, + projectId: existing.id, + title: existing.title, + ...(prompt + ? await draftWithPrompt(existing.environmentId, existing.id, prompt).then( + (draftId) => ({ draftId }), + () => ({}), + ) + : {}), + }, + originRoute, + ); + return true; + }; +} + +function useCreateProject(environment: EnvironmentOption | null) { + const openNewTaskDraft = useOpenNewTaskDraft(); + const navigation = useNavigation(); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const openExistingProject = useOpenExistingProject(environment); + + return async ( + workspaceRoot: string, + originRoute = getActiveRoute(navigation), + lookupPath = workspaceRoot, + ) => { if ( !environment || !canCreateProjectInEnvironment(environment.connectionState) || @@ -752,33 +831,7 @@ function useCreateProject(environment: EnvironmentOption | null) { return; } - const existing = findExistingAddProject({ - projects, - environmentId: environment.environmentId, - path: workspaceRoot, - }); - if (existing) { - // Adding an archived project's folder again brings the project back. - const unarchived = - existing.archivedAt == null || - ( - await updateProject({ - environmentId: existing.environmentId, - input: { projectId: existing.id, archived: false }, - }) - )._tag === "Success"; - Dialog.alert( - "Project already exists", - unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, - ); - openNewTaskDraft( - { - environmentId: existing.environmentId, - projectId: existing.id, - title: existing.title, - }, - originRoute, - ); + if (await openExistingProject(lookupPath, originRoute)) { return; } @@ -1313,8 +1366,9 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st environment?.environmentId ?? null, AuthOrchestrationOperateScope, ); + const navigation = useNavigation(); const createProject = useCreateProject(environment); - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = useBrowsePathInput(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1333,7 +1387,11 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st } setIsSubmitting(true); - const result = await createProject(resolved.path); + const originRoute = getActiveRoute(navigation); + const lookupPath = resolved.path.startsWith("~") + ? await resolveHomePath(resolved.path) + : resolved.path; + const result = await createProject(resolved.path, originRoute, lookupPath); if (result && AsyncResult.isFailure(result)) { setError(errorMessage(Cause.squash(result.cause))); } @@ -1404,11 +1462,9 @@ export function AddProjectDestinationScreen(props: { ? getCloneDirectoryPath(remoteUrl, true, repositoryName) : null; const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName; - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput( - environment, - cloneDirectoryName, - ghqDirectoryPath ?? repositoryName, - ); + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = + useBrowsePathInput(environment, cloneDirectoryName, ghqDirectoryPath ?? repositoryName); + const openExistingProject = useOpenExistingProject(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1436,6 +1492,15 @@ export function AddProjectDestinationScreen(props: { const originRoute = getActiveRoute(navigation); setIsSubmitting(true); + if ( + await openExistingProject(await resolveHomePath(resolved.path), originRoute, { + remoteUrl, + prompt: prompt ?? null, + }) + ) { + setIsSubmitting(false); + return; + } const title = inferProjectTitleFromPath(resolved.path); const startResult = await startProjectClone({ environmentId: environment.environmentId, diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.ts index e6c04f192b417..132501b60a240 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestActions.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestActions.ts @@ -33,6 +33,10 @@ export const MERGE_METHODS = { description: "Keep the commits and add a merge commit.", }, rebase: { title: "Rebase and merge", description: "Add the commits without a merge commit." }, + "fast-forward": { + title: "Fast-forward merge", + description: "Add the commits as they are. Needs the branch to contain the base.", + }, } as const satisfies Record; export function pullRequestActionLabel( diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index 4e500887cffc3..f2164bf49f99f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -3,6 +3,7 @@ import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useMemo, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; +import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; @@ -86,13 +87,14 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const handleNativePaste = useNativePaste((uris) => { void (async () => { try { - const images = await convertPastedImagesToAttachments({ + const result = await convertPastedImagesToAttachments({ uris, existingCount: attachments.length, }); - if (images.length > 0) { - setAttachments((current) => [...current, ...images]); + if (result.attachments.length > 0) { + setAttachments((current) => [...current, ...result.attachments]); } + if (result.error) Dialog.alert("Could not paste image", result.error); } catch (error) { console.error("[review comment] error converting pasted images", error); } diff --git a/apps/mobile/src/features/settings/settings-navigation.ts b/apps/mobile/src/features/settings/settings-navigation.ts index b97bc948c0a2b..a414d1014a695 100644 --- a/apps/mobile/src/features/settings/settings-navigation.ts +++ b/apps/mobile/src/features/settings/settings-navigation.ts @@ -91,6 +91,24 @@ export function settingsNavigationState, + current: NavigationState | undefined, +) { + const top = link.routes.at(-1); + if (!current || !top || top.state || !isSettingsRoute(top.name)) return undefined; + const page = top.name === "Settings" ? undefined : (top.name as SettingsPageName); + return { + type: "RESET" as const, + payload: settingsNavigationState(current, page, top.params), + target: current.key, + }; +} + /** Opens one Settings page in the Settings tab, from anywhere outside it. */ export function openSettings( navigation: RootStackNavigation, diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx index 229ef86273b8d..aee091d9f598e 100644 --- a/apps/mobile/src/features/threads/LinkRequestCard.tsx +++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx @@ -299,8 +299,8 @@ function LinkRequestSheet(props: { > - Agents here can then launch, message and wait on threads there. It appears in that - machine's Connections, where it can be revoked. + Agents here can then launch, message and wait on threads there. It appears under + Authorized clients in that machine's Sharing & access, where it can be revoked. {item.url !== undefined && target.kind === "machine" ? ( @@ -375,7 +375,7 @@ function LinkRequestSheet(props: { {useExisting ? ( This environment is already linked to {targetName}. The agent can use that link as it - is; change its access in Settings → Connections. + is; change its access in Settings → Environments. ) : target.kind === "none" ? null : ( <> @@ -394,8 +394,8 @@ function LinkRequestSheet(props: { spellCheck={false} /> - Create a link on {targetName}: Settings → Connections → Create link, then paste - its code here. + Create a link on {targetName}: Settings → Sharing & access → Authorized clients → + Create link, then paste its code here. )} diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsx index 2c369c1e5b7bc..b8fa753188608 100644 --- a/apps/mobile/src/features/threads/QuestionAttachments.tsx +++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx @@ -109,14 +109,17 @@ export function QuestionAttachments(props: { uris, existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0, }) - .then(async (images) => { + .then(async (result) => { if ( scope.active && (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0 ) { - if (append(key, images) > 0) - Dialog.alert("Could not paste image", "Too many attachments."); - } else await releaseUnusedComposerAttachmentFiles(images); + const problems = [ + ...(result.error ? [result.error] : []), + ...(append(key, result.attachments) > 0 ? ["Too many attachments."] : []), + ]; + if (problems.length) Dialog.alert("Could not paste image", problems.join("\n\n")); + } else await releaseUnusedComposerAttachmentFiles(result.attachments); }) .catch((error) => Dialog.alert( diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index e1c51b7f524b5..fb0db83a4dab7 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -1,10 +1,7 @@ import { useActiveNewTask } from "../../state/active-new-task"; import { ThreadUndoNotice } from "../home/ThreadUndoNotice"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { - pickableProjectGroups, - resolveScratchProjectScopeKey, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { useAppearancePreferences, useAndroidFloatingTabs, @@ -48,7 +45,7 @@ import { requestThreadMessageJump } from "./threadMessageJump"; import { useThreadListSearchMatches } from "./useThreadListSearchMatches"; import { useHomeListOptions } from "../home/home-list-options"; import { buildHomeListFilterMenuItems } from "../home/home-list-filter-menu"; -import { buildHomeProjectScopes } from "../home/homeThreadList"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; import { useThreadListActions } from "../home/useThreadListActions"; @@ -172,12 +169,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ) ? [options.selectedEnvironmentId] : []; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { - sidebarProjectGroupingMode: options.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }); const projectScopes = useMemo( () => buildHomeProjectScopes({ @@ -206,9 +197,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ), [projectScopes], ); - // An archived project's filter reads as all projects, matching the filter menu. - const selectedProjectScope = - pickableProjectGroups(projectScopes).find((scope) => scope.key === resolvedProjectKey) ?? null; + const selectedProjectScope = resolveHomeProjectFilterScope(projectScopes, projects, options); const threadSearch = useThreadSearch( searchEnvironmentIds, props.searchQuery, diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx index 3b91dbb122ffd..05ccf29b2ae70 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx @@ -4,6 +4,7 @@ import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; import { createEnvironmentSubscriptionAtomFamily } from "@t3tools/client-runtime/state/runtime"; import { AuthFilesystemReadScope, + DEFAULT_SERVER_SETTINGS, EnvironmentId, ProjectId, type VcsListRefsResult, @@ -32,6 +33,9 @@ const mocks = vi.hoisted(() => ({ retargetDraft: vi.fn(), writeSettings: vi.fn(), writeText: vi.fn(), + serverConfig: vi.fn(), + openScratch: vi.fn(), + prepareTriage: vi.fn(), })); vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { @@ -43,7 +47,7 @@ vi.mock("../../state/atom-registry", () => ({ vi.mock("../../state/entities", () => ({ useProjects: mocks.projects, useThreadShells: () => [], - useEnvironmentServerConfig: () => null, + useEnvironmentServerConfig: () => mocks.serverConfig() ?? null, useServerConfigs: () => new Map(), })); vi.mock("../../state/vcs", () => ({ @@ -66,7 +70,8 @@ vi.mock("../../state/project-grouping", () => ({ useMobileProjectGroupingSettings: () => ({ sidebarProjectGroupingMode: "none" }), })); vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); -vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() })); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.openScratch })); +vi.mock("../triage/usePrepareTriage", () => ({ usePrepareTriage: () => mocks.prepareTriage })); vi.mock("../../state/use-remote-environment-registry", () => ({ useSavedRemoteConnections: () => ({ savedConnectionsById: {} }), useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }), @@ -362,3 +367,78 @@ it("uses cached repository capability and branch defaults while offline", async expect(screen.current.draftKey).toBe(draftKey); expect(screen.current.selectedBranchName).toBe("main"); }); + +const playbookPrompt = (machine: string) => + `Read [triage-playbook.md](/${machine}/triage-playbook.md) and follow it. `; + +/** A triage draft on machine one's No project home; machine two opens its own. */ +async function renderTriageDraft(screen: ReturnType) { + mocks.serverConfig.mockReturnValue({ + scratchWorkspaceRoot: "/a", + providers: [], + settings: DEFAULT_SERVER_SETTINGS, + }); + mocks.openScratch.mockResolvedValue({ _tag: "Success", value: screen.projects[2] }); + await screen.render(true); + act(() => screen.current.setPrompt(`${playbookPrompt("one")}It is slow.`)); +} + +it("takes a triage draft's session along when its machine changes", async () => { + using screen = setup(); + await renderTriageDraft(screen); + mocks.prepareTriage.mockResolvedValue({ + _tag: "Success", + value: { prompt: playbookPrompt("two") }, + }); + + await act(async () => { + await screen.current.switchEnvironment(EnvironmentId.make("two")); + }); + + expect(screen.current.prompt).toBe(`${playbookPrompt("two")}It is slow.`); + expect(screen.current.selectedProject).toEqual(screen.projects[2]); +}); + +it.each([ + [ + "a project is picked", + 1, + (flow: ReturnType, picked: EnvironmentProject) => + flow.setProject(picked), + ], + [ + "a send starts and ends", + 0, + (flow: ReturnType) => { + flow.setSubmitting(true); + flow.setSubmitting(false); + }, + ], +] as const)( + "leaves a triage draft alone when %s while its new machine prepares", + async (_name, expectedProject, interrupt) => { + using screen = setup(); + await renderTriageDraft(screen); + let finishPreparing!: (result: unknown) => void; + mocks.prepareTriage.mockReturnValue( + new Promise((resolve) => { + finishPreparing = resolve; + }), + ); + + let switching!: Promise; + act(() => { + switching = screen.current.switchEnvironment(EnvironmentId.make("two")); + }); + await act(async () => interrupt(screen.current, screen.projects[1]!)); + let switched = true; + await act(async () => { + finishPreparing({ _tag: "Success", value: { prompt: playbookPrompt("two") } }); + switched = await switching; + }); + + expect(switched).toBe(false); + expect(screen.current.prompt).toBe(`${playbookPrompt("one")}It is slow.`); + expect(screen.current.selectedProject).toEqual(screen.projects[expectedProject]); + }, +); diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 5a8d7a1aa78f4..5852206095a8f 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -19,6 +19,7 @@ import { ThreadId, } from "@t3tools/contracts"; import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences"; +import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; @@ -88,7 +89,7 @@ import { resolveNewTaskBranchWorktreePath, resolveNewTaskLocalWorkspaceSelection, } from "./new-task-context-presentation"; -import { resolveEnvironmentProjectMatch } from "./new-task-project-selection"; +import { isSameRepository, resolveEnvironmentProjectMatch } from "./new-task-project-selection"; import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults"; import { resolveNewThreadRuntimeMode } from "./thread-settings-options"; import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation"; @@ -102,6 +103,7 @@ import { stampedEnvironmentProjectsLoading, updateNewTaskFlowState, } from "./new-task-flow-state"; +import { usePrepareTriage } from "../triage/usePrepareTriage"; import { useEnvironmentShellReadiness } from "../../state/shell"; import { useConnectionsReady, useWorkspaceEnvironments } from "../../state/workspace"; @@ -558,11 +560,14 @@ export function NewTaskFlowProvider( replaceComposerDraftAttachments(selectedProjectDraftKey, []); }; - const carryDraftContentTo = (project: EnvironmentProject): string => { + const carryDraftContentTo = ( + project: EnvironmentProject, + options?: Parameters[2], + ): string => { const target = { environmentId: project.environmentId, projectId: project.id }; const current = readFlow().draftKey; if (current !== null && isNewTaskDraftKey(current)) { - retargetNewTaskDraft(current, target); + retargetNewTaskDraft(current, target, options); return current; } return createNewTaskDraft(target); @@ -582,13 +587,19 @@ export function NewTaskFlowProvider( selectedProject, ); updateFlow({ - draftKey: match ? carryDraftContentTo(match) : readFlow().draftKey, + // A name or title match may be another repository, which must not receive the PR checkout. + draftKey: match + ? carryDraftContentTo(match, { + keepPullRequestWorkspace: isSameRepository(match, selectedProject), + }) + : readFlow().draftKey, environmentId, projectKey: match ? scopedProjectKey(match.environmentId, match.id) : null, }); }; const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false }); + const prepareTriage = usePrepareTriage(); const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState( null, ); @@ -606,11 +617,27 @@ export function NewTaskFlowProvider( const request = {}; latestSwitchRef.current = request; setSwitchingToEnvironmentId(environmentId); - const result = await openScratch({ environmentId, input: {} }); + // A triage draft takes its session along: the playbook and context files + // exist only on the machine that prepared them. + const { draftKey, projectKey } = readFlow(); + const triage = + draftKey !== null && isTriagePrompt(getComposerDraftSnapshot(draftKey).text) + ? await prepareTriage(environmentId) + : null; + const result = + triage?._tag === "Failure" ? triage : await openScratch({ environmentId, input: {} }); if (latestSwitchRef.current !== request) return false; latestSwitchRef.current = null; setSwitchingToEnvironmentId(null); + // A project picked while this waited stands. + if (readFlow().projectKey !== projectKey) return false; if (result._tag === "Success") { + if (triage?._tag === "Success" && draftKey !== null && readFlow().draftKey === draftKey) { + // Read now, so text typed while the machine prepared the session is kept. + const text = getComposerDraftSnapshot(draftKey).text; + const nextText = replaceTriagePlaybookLink(text, triage.value.prompt); + if (nextText !== text) setComposerDraftText(draftKey, nextText); + } setProject(result.value); return true; } @@ -620,7 +647,9 @@ export function NewTaskFlowProvider( "Could not switch machine", error instanceof Error ? error.message - : "The folder for threads without a project could not be created.", + : triage?._tag === "Failure" + ? "The server could not prepare triage." + : "The folder for threads without a project could not be created.", ); } return false; @@ -884,7 +913,14 @@ export function NewTaskFlowProvider( appendAttachments, removeAttachment, clearAttachments, - setSubmitting: (value: boolean) => updateFlow({ submitting: value }), + setSubmitting: (value: boolean) => { + // A send takes the draft as it is, so a machine switch still waiting is dropped. + if (value) { + latestSwitchRef.current = null; + setSwitchingToEnvironmentId(null); + } + updateFlow({ submitting: value }); + }, loadBranches, setRuntimeMode, setSelectedModelOptions, diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.ts index 99cf9e7d37ef4..82533a3c91e74 100644 --- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts +++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts @@ -5,7 +5,9 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import type { HomeProjectScope } from "../home/homeThreadList"; import { getProjectScopeSelectionTarget, + isSameRepository, newTaskDestination, + newTaskFilteredProject, resolveDraftProjectSelection, resolveEnvironmentProjectMatch, resolveNewTaskScratchOption, @@ -77,6 +79,37 @@ describe("getProjectScopeSelectionTarget", () => { }); }); +describe("newTaskFilteredProject", () => { + it("never starts in an archived copy of the filtered project", () => { + const mac = { ...makeProject("t3code", "mac"), archivedAt: "2026-01-01T00:00:00.000Z" }; + const server = makeProject("t3code", "server"); + expect( + newTaskFilteredProject( + makeScope([mac, server]), + null, + new Set([mac.environmentId, server.environmentId]), + { environmentId: "mac", projectId: "t3code" }, + ), + ).toEqual({ environmentId: "server", projectId: "t3code" }); + }); + + it("prefers the remembered copy of the filtered project", () => { + const mac = makeProject("t3code", "mac"); + const server = makeProject("t3code", "server"); + const connected = new Set([mac.environmentId, server.environmentId]); + const filtered = (last?: { readonly environmentId: string; readonly projectId: string }) => + newTaskFilteredProject(makeScope([mac, server]), null, connected, last); + expect(filtered({ environmentId: "server", projectId: "t3code" })).toEqual({ + environmentId: "server", + projectId: "t3code", + }); + expect(filtered({ environmentId: "server", projectId: "other" })).toEqual({ + environmentId: "mac", + projectId: "t3code", + }); + }); +}); + describe("resolveEnvironmentProjectMatch", () => { it("follows the same repository onto the target machine", () => { const selected = makeProject("t3code", "mac", { repositoryKey: "github.com/t3tools/t3code" }); @@ -85,6 +118,7 @@ describe("resolveEnvironmentProjectMatch", () => { makeProject("t3code-clone", "server", { repositoryKey: "github.com/t3tools/t3code" }), ]; expect(resolveEnvironmentProjectMatch(target, selected)).toBe(target[1]); + expect(isSameRepository(target[1]!, selected)).toBe(true); }); it("falls back to workspace basename, then title, for unindexed projects", () => { @@ -94,6 +128,7 @@ describe("resolveEnvironmentProjectMatch", () => { makeProject("srv", "server", { workspaceRoot: "/home/me/t3code" }), ]; expect(resolveEnvironmentProjectMatch(byBasename, selected)).toBe(byBasename[1]); + expect(isSameRepository(byBasename[1]!, selected)).toBe(false); const byTitle = [ makeProject("other", "server"), @@ -115,6 +150,7 @@ describe("resolveEnvironmentProjectMatch", () => { const unindexed = makeProject("unindexed", "server", { workspaceRoot: "/srv/t3code" }); expect(resolveEnvironmentProjectMatch([fork, unindexed], selected)).toBe(unindexed); expect(resolveEnvironmentProjectMatch([fork], selected)).toBe(fork); + expect(isSameRepository(fork, selected)).toBe(false); }); }); @@ -173,6 +209,7 @@ describe("newTaskDestination", () => { readonly useLastProject: boolean | undefined; readonly projects: ReadonlyArray; readonly current?: EnvironmentProject; + readonly filtered?: EnvironmentProject; readonly last?: { readonly environmentId: string; readonly projectId: string }; }) { return newTaskDestination({ @@ -183,17 +220,22 @@ describe("newTaskDestination", () => { environmentId: options.current.environmentId, projectId: options.current.id, }, + filteredProject: options.filtered && { + environmentId: options.filtered.environmentId, + projectId: options.filtered.id, + }, lastProject: options.last, }); } - it("starts in the current thread's project ahead of the remembered one", () => { + it("starts in the current thread's project ahead of the filtered and remembered ones", () => { const projects = [makeProject("remembered"), makeProject("current", "other-environment")]; expect( destination({ useLastProject: true, projects, current: projects[1], + filtered: projects[0], last: { environmentId: "environment", projectId: "remembered" }, }), ).toEqual({ @@ -201,6 +243,20 @@ describe("newTaskDestination", () => { }); }); + it("starts in the thread list's filtered project ahead of the remembered one", () => { + const projects = [makeProject("bravo"), makeProject("alpha")]; + expect( + destination({ + useLastProject: true, + projects, + filtered: projects[1], + last: { environmentId: "environment", projectId: "bravo" }, + }), + ).toEqual({ + draft: { requestId: "request", environmentId: "environment", projectId: "alpha" }, + }); + }); + it("opens the picker for an archived last project, but keeps an archived current one", () => { const archived = { ...makeProject("archived"), archivedAt: "2026-01-01T00:00:00.000Z" }; expect( @@ -262,6 +318,7 @@ describe("newTaskDestination", () => { useLastProject: false, projects: [only], current: only, + filtered: only, last: { environmentId: "environment", projectId: "only" }, }), ).toEqual(picker); diff --git a/apps/mobile/src/features/threads/new-task-project-selection.ts b/apps/mobile/src/features/threads/new-task-project-selection.ts index 93c8f1d5f51d6..2fa21eba1e234 100644 --- a/apps/mobile/src/features/threads/new-task-project-selection.ts +++ b/apps/mobile/src/features/threads/new-task-project-selection.ts @@ -117,6 +117,19 @@ export function resolveEnvironmentProjectMatch( ); } +/** Both projects have a known repository identity, and it is the same one. */ +export function isSameRepository( + left: EnvironmentProject | null, + right: EnvironmentProject | null, +): boolean { + return ( + left?.repositoryIdentity != null && + right?.repositoryIdentity != null && + repositoryGroupingKeyOf(left.repositoryIdentity) === + repositoryGroupingKeyOf(right.repositoryIdentity) + ); +} + export function resolveDraftProjectSelection( selectedProjectKey: string | null, projects: ReadonlyArray, @@ -147,11 +160,35 @@ export function resolveDraftProjectSelection( type ProjectRef = { readonly environmentId: string; readonly projectId: string }; +/** The live copy of the thread list's filtered project a new thread starts in: the remembered one if it is a copy. */ +export function newTaskFilteredProject( + scope: HomeProjectScope, + preferredEnvironmentId: EnvironmentId | null, + connectedEnvironmentIds: ReadonlySet, + lastProject: ProjectRef | undefined, +): ProjectRef | undefined { + const live = scope.projects.filter((project) => project.archivedAt == null); + if (live.length === 0) return undefined; + const project = + live.find( + (candidate) => + candidate.environmentId === lastProject?.environmentId && + candidate.id === lastProject.projectId, + ) ?? + getProjectScopeSelectionTarget( + { ...scope, projects: live }, + preferredEnvironmentId, + connectedEnvironmentIds, + ); + return { environmentId: project.environmentId, projectId: project.id }; +} + export function newTaskDestination(options: { readonly projects: ReadonlyArray; readonly requestId: string; readonly useLastProject: boolean | undefined; readonly currentProject: ProjectRef | undefined; + readonly filteredProject: ProjectRef | undefined; readonly lastProject: ProjectRef | undefined; }) { const find = (ref: ProjectRef | undefined) => @@ -164,7 +201,9 @@ export function newTaskDestination(options: { const project = options.useLastProject === false ? undefined - : (find(options.currentProject) ?? (last?.archivedAt == null ? last : undefined)); + : (find(options.currentProject) ?? + find(options.filteredProject) ?? + (last?.archivedAt == null ? last : undefined)); return project ? { draft: { 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 1e66bf4ee2c8e..a77f7089c97bd 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.ts +++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts @@ -1,3 +1,4 @@ +import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; import * as Dialog from "../../components/ui/Dialog"; import type { EnvironmentId, @@ -358,7 +359,7 @@ export function useComposerCommandMenu({ if (trigger.kind === "pull-request") { return pullRequestSearch.entries.map((entry) => ({ - id: `pr:${entry.projectId}:${entry.repository}:${entry.number}`, + id: `pr:${entry.projectId}:${threadPullRequestKeyOf(entry)}`, type: "pull-request", pullRequest: { number: entry.number, diff --git a/apps/mobile/src/features/triage/usePrepareTriage.ts b/apps/mobile/src/features/triage/usePrepareTriage.ts new file mode 100644 index 0000000000000..94194275b2cc6 --- /dev/null +++ b/apps/mobile/src/features/triage/usePrepareTriage.ts @@ -0,0 +1,19 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import Constants from "expo-constants"; + +import { authClientMetadata } from "../../lib/authClientMetadata"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; + +/** + * Asks a machine to prepare a triage session. The result carries the prompt + * that links its playbook; the caller reports a failure. + */ +export function usePrepareTriage() { + const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false }); + return (environmentId: EnvironmentId) => + prepare({ + environmentId, + input: { client: authClientMetadata(Constants.expoConfig?.version) }, + }); +} diff --git a/apps/mobile/src/features/triage/useStartTriage.ts b/apps/mobile/src/features/triage/useStartTriage.ts index eb9eef24b2670..7f8851e39a4ed 100644 --- a/apps/mobile/src/features/triage/useStartTriage.ts +++ b/apps/mobile/src/features/triage/useStartTriage.ts @@ -6,12 +6,9 @@ import { import type { EnvironmentId } from "@t3tools/contracts"; import { useNavigation } from "@react-navigation/native"; import * as Clipboard from "expo-clipboard"; -import Constants from "expo-constants"; import * as Dialog from "../../components/ui/Dialog"; -import { authClientMetadata } from "../../lib/authClientMetadata"; import { projectEnvironment } from "../../state/projects"; -import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { createNewTaskDraft, @@ -19,6 +16,7 @@ import { waitForComposerDraftsLoaded, } from "../../state/use-composer-drafts"; import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; +import { usePrepareTriage } from "./usePrepareTriage"; const CLI_COMMAND = "npx t3 triage"; @@ -29,7 +27,7 @@ const CLI_COMMAND = "npx t3 triage"; export function useStartTriage() { const navigation = useNavigation(); const selectDetail = useSelectWorkspaceDetail(); - const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false }); + const prepare = usePrepareTriage(); const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false }); const fail = (message: string) => @@ -77,10 +75,7 @@ export function useStartTriage() { } return; } - const prepared = await prepare({ - environmentId, - input: { client: authClientMetadata(Constants.expoConfig?.version) }, - }); + const prepared = await prepare(environmentId); if (prepared._tag === "Failure") { if (!isAtomCommandInterrupted(prepared)) { pipe( diff --git a/apps/mobile/src/lib/composerImagePreview.test.ts b/apps/mobile/src/lib/composerImagePreview.test.ts index 84bcc13bbf7d1..6e428d421efaa 100644 --- a/apps/mobile/src/lib/composerImagePreview.test.ts +++ b/apps/mobile/src/lib/composerImagePreview.test.ts @@ -32,7 +32,7 @@ vi.mock("expo-file-system", () => ({ return mocks.write(content, options); } async move(destination: { uri: string }) { - mocks.files.delete(this.uri); + if (!mocks.files.delete(this.uri)) throw new Error("source missing"); mocks.files.add(destination.uri); this.uri = destination.uri; } @@ -103,4 +103,32 @@ describe("materializedPreviewAtom", () => { expect(await materialize()).toBe("file:///cache/t3-composer-previews/image-failed.png"); expect(mocks.write).toHaveBeenCalledTimes(2); }); + + it("shares one write when the atom is rebuilt while its preview is still being written", async () => { + const attachment: DraftComposerImageAttachment = { + id: "image-rebuilt", + type: "image", + name: "pasted.jpeg", + mimeType: "image/jpeg", + sizeBytes: 3, + previewUri: "data:image/jpeg;base64,AAAA", + }; + const read = () => { + const registry = AtomRegistry.make(); + const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment)); + const unmount = registry.mount(atom); + return vi + .waitFor(() => { + const result = registry.get(atom); + expect(AsyncResult.isSuccess(result)).toBe(true); + return AsyncResult.isSuccess(result) ? result.value : undefined; + }) + .finally(unmount); + }; + + expect(await Promise.all([read(), read()])).toEqual([ + "file:///cache/t3-composer-previews/image-rebuilt.jpg", + "file:///cache/t3-composer-previews/image-rebuilt.jpg", + ]); + }); }); diff --git a/apps/mobile/src/lib/composerImagePreview.ts b/apps/mobile/src/lib/composerImagePreview.ts index 6c27d3889bf62..80a9a0d6d39ef 100644 --- a/apps/mobile/src/lib/composerImagePreview.ts +++ b/apps/mobile/src/lib/composerImagePreview.ts @@ -32,6 +32,18 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise>(); + +// A render reads the atom before its effect subscribes, so the registry can drop and rebuild it +// mid-write; a second writer would delete the first one's partial file and fail its own move. +function materializePreviewOnce(id: string, dataUrl: string): Promise { + const pending = inFlightPreviews.get(id); + if (pending) return pending; + const next = materializeDataUrlPreview(id, dataUrl).finally(() => inFlightPreviews.delete(id)); + inFlightPreviews.set(id, next); + return next; +} + class ImagePreviewCacheError extends Schema.TaggedError()( "ImagePreviewCacheError", { cause: Schema.Defect() }, @@ -59,7 +71,7 @@ export class MaterializedPreviewKey implements Equal.Equal { export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) => Atom.make( Effect.tryPromise({ - try: () => materializeDataUrlPreview(attachment.id, attachment.previewUri), + try: () => materializePreviewOnce(attachment.id, attachment.previewUri), catch: (cause) => new ImagePreviewCacheError({ cause }), }).pipe( Effect.catch((error) => diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index ac01bb09b4261..c723293c85270 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -121,6 +121,15 @@ vi.mock("./uuid", () => ({ import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; +function oversizedPng(): string { + const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png); + png.write("IHDR", 12); + png.writeUInt32BE(2000, 16); + png.writeUInt32BE(2000, 20); + return png.toString("base64"); +} + describe("native pasted image cleanup", () => { beforeEach(() => { files.clear(); @@ -131,7 +140,10 @@ describe("native pasted image cleanup", () => { const uri = "content://media/external/images/media/42"; files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" }); - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }); + const { attachments } = await convertPastedImagesToAttachments({ + uris: [uri], + existingCount: 0, + }); expect(attachments).toEqual([ expect.objectContaining({ @@ -149,7 +161,10 @@ describe("native pasted image cleanup", () => { files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" }); manipulator.state.sourceSize = { width: 100, height: 100 }; - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }); + const { attachments } = await convertPastedImagesToAttachments({ + uris: [uri], + existingCount: 0, + }); expect(attachments).toEqual([ expect.objectContaining({ @@ -171,7 +186,10 @@ describe("native pasted image cleanup", () => { Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4, ); - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }); + const { attachments } = await convertPastedImagesToAttachments({ + uris: [uri], + existingCount: 0, + }); expect(attachments).toEqual([]); expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); @@ -183,7 +201,7 @@ describe("native pasted image cleanup", () => { "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png"; files.set(uri, { base64: "aGVsbG8=", deleted: false }); - const attachments = await convertPastedImagesToAttachments({ + const { attachments } = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0, }); @@ -216,6 +234,53 @@ describe("native pasted image cleanup", () => { expect(files.get(overflow)?.deleted).toBe(true); expect(files.get(userOwned)?.deleted).toBe(false); }); + + it("re-renders an over-limit paste whose dimensions already fit, like the photo picker", async () => { + const uri = + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/photo.png"; + files.set(uri, { base64: oversizedPng(), deleted: false }); + manipulator.state.sourceSize = { width: 2000, height: 2000 }; + + const { attachments } = await convertPastedImagesToAttachments({ + uris: [uri], + existingCount: 0, + }); + + expect(attachments).toHaveLength(1); + expect(attachments[0]?.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES); + expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); + }); + + it("keeps the readable images of a paste and still reports the one it dropped", async () => { + const gone = + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/gone.png"; + const kept = + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/kept.png"; + files.set(kept, { base64: "aGVsbG8=", deleted: false }); + + const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 }); + + expect(result.attachments).toEqual([ + expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }), + ]); + expect(result.error).toBe("Could not read a pasted image."); + }); + + it("reports the size limit when even the JPEG re-render is too large", async () => { + const uri = + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/huge.png"; + files.set(uri, { base64: oversizedPng(), deleted: false }); + manipulator.state.sourceSize = { width: 2000, height: 2000 }; + manipulator.state.renderedBase64 = oversizedPng(); + + const result = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }); + + expect(result).toEqual({ + attachments: [], + error: "A pasted image exceeds the 10 MB attachment limit.", + }); + expect(files.get(uri)?.deleted).toBe(true); + }); }); describe("persistComposerAttachmentFile", () => { diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 5b8b0b803d3fa..7f7718f540ca2 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -572,10 +572,14 @@ function isOwnedPastedImageUri(uri: string): boolean { export async function convertPastedImagesToAttachments(input: { readonly uris: ReadonlyArray; readonly existingCount: number; -}): Promise> { +}): Promise<{ + readonly attachments: ReadonlyArray; + readonly error: string | null; +}> { const { File } = await import("expo-file-system"); const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount; - const results: DraftComposerImageAttachment[] = []; + const attachments: DraftComposerImageAttachment[] = []; + let error: string | null = null; for (const [index, uri] of input.uris.entries()) { const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : []; @@ -588,31 +592,46 @@ export async function convertPastedImagesToAttachments(input: { const sourceMimeType = reportedMimeType?.startsWith("image/") ? reportedMimeType : mimeTypeFromUri(uri); - const mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType) + let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType) ? sourceMimeType : "image/jpeg"; const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri); - if (rendered !== null) { - temporaryUris.push(rendered.uri); - } const pastedBase64 = rendered?.base64 ?? (await file.base64()); const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 })); - const base64 = fitted?.base64 ?? pastedBase64; + if (fitted !== null) { + temporaryUris.push(fitted.uri); + } + let base64 = fitted?.base64 ?? pastedBase64; + if ( + rendered === null && + estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + ) { + const jpeg = await renderPhoto(uri); + temporaryUris.push(jpeg.uri); + mimeType = "image/jpeg"; + base64 = jpeg.base64; + } const sizeBytes = estimateBase64ByteSize(base64); if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + error = + sizeBytes > 0 + ? "A pasted image exceeds the 10 MB attachment limit." + : "Could not read a pasted image."; continue; } - results.push({ + const dataUrl = `data:${mimeType};base64,${base64}`; + attachments.push({ id: uuidv4(), type: "image", name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, mimeType, sizeBytes, - dataUrl: `data:${mimeType};base64,${base64}`, - previewUri: `data:${mimeType};base64,${base64}`, + dataUrl, + previewUri: dataUrl, }); - } catch (error) { - console.warn("Failed to read pasted image", uri, error); + } catch (cause) { + console.warn("Failed to read pasted image", uri, cause); + error = "Could not read a pasted image."; } finally { for (const temporaryUri of temporaryUris) { try { @@ -627,5 +646,5 @@ export async function convertPastedImagesToAttachments(input: { } } - return results; + return { attachments, error }; } diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 86e7f3f7182ac..6de60afc1cb26 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -54,7 +54,36 @@ it("shows a captured MCP app for a failed deferred write", () => { input: {}, output: { t3McpApp: mcpApp, result: { content: [], isError: true } }, }; - expect(buildThreadFeed([projected(item, 0)])).toMatchObject([{ type: "mcp-app", app: mcpApp }]); + expect(buildThreadFeed([projected(item, 0)])).toMatchObject([ + { type: "activity-group" }, + { type: "mcp-app", app: mcpApp }, + ]); +}); + +it("keeps an MCP app call's tool activity beside its app card", () => { + const mcpApp = { + attachmentId: "repro-app-html", + server: "repro", + tool: "aggregate_rum_events", + resourceUri: "ui://repro/dataviz", + }; + const item: OrchestrationV2TurnItem = { + ...base("repro-app", "2026-08-29T00:00:00.000Z", 1), + type: "dynamic_tool", + toolName: "repro.aggregate_rum_events", + input: { query: "@type:view" }, + output: { + t3McpApp: mcpApp, + result: { content: [{ type: "text", text: "Notice\nview\tcount\n/home\t42" }] }, + }, + }; + const feed = buildThreadFeed([projected(item, 0)]); + expect(feed).toContainEqual(expect.objectContaining({ type: "mcp-app", app: mcpApp })); + const activities = feed.flatMap((entry) => + entry.type === "activity-group" ? entry.activities : [], + ); + expect(activities).toHaveLength(1); + expect(activities[0]?.getFullDetail()).toContain("@type:view"); }); it("keeps historical plan detail accessible from its paged turn item", () => { @@ -1468,6 +1497,16 @@ describe("buildThreadFeed", () => { phase === "final_answer", ); } + const confirmed = { ...answer, phase: "final_answer" as const }; + const continued = buildThreadFeed( + [user, confirmed, passed, final].map((item, index) => projected(item, index)), + ); + expect( + deriveThreadFeedPresentation(continued, null, new Set()).some( + (row) => row.type === "message" && row.message.id === answer.messageId, + ), + ).toBe(true); + expect(rows([user, confirmed, passed, final], "zen")).toEqual(["user", "answer", "final"]); expect(rows([user, steer, step, passed, final], "zen")).toEqual(["user", "steer", "final"]); expect(rows([user, steer, answer, step], "zen", running)).toEqual([ "user", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 7591b0060985b..ec755ce12a2c7 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -317,7 +317,7 @@ const projectedEntriesCache = new WeakMap< OrchestrationV2ProjectedTurnItem, { readonly attemptId: RunAttemptId | null; - readonly entry: RawThreadFeedEntry; + readonly entries: ReadonlyArray; } >(); const localMessageEntriesCache = new WeakMap< @@ -1103,21 +1103,17 @@ function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): R : null; } -function answersBeforeSteers(feed: ReadonlyArray): ReadonlySet { +function finalAnswerIds(feed: ReadonlyArray): ReadonlySet { const ids = new Set(); - let previous: ThreadFeedEntry | undefined; for (const entry of feed) { if ( entry.type === "message" && - isSteerMessage(entry.message) && - previous?.type === "message" && - previous.message.role === "assistant" && - previous.message.projectedItem?.item.type === "assistant_message" && - previous.message.projectedItem.item.phase === "final_answer" + entry.message.role === "assistant" && + entry.message.projectedItem?.item.type === "assistant_message" && + entry.message.projectedItem.item.phase === "final_answer" ) { - ids.add(previous.message.id); + ids.add(entry.message.id); } - previous = entry; } return ids; } @@ -1129,7 +1125,7 @@ function deriveThreadFeedRunFolds( feedFailedRunIds: ReadonlySet, ): ReadonlyMap { const terminalAssistantMessageIdByRun = new Map(); - const retainedAnswerIds = answersBeforeSteers(feed); + const retainedAnswerIds = finalAnswerIds(feed); const interruptedRunIds = new Set(); const failedRunIds = new Set(feedFailedRunIds); const promptIndexByRunId = new Map(); @@ -1523,7 +1519,7 @@ function zenAnswerMessageIds( ): ReadonlySet { const replies: Array<{ readonly message: ThreadFeedMessage; readonly index: number }> = []; const lastReplyByResponse = new Map(); - const steerAnswers = new Set(answersBeforeSteers(feed)); + const keptAnswers = new Set(finalAnswerIds(feed)); let userMessages = 0; let awaitingReply = false; let candidate: MessageId | null = null; @@ -1538,7 +1534,7 @@ function zenAnswerMessageIds( } const reply = entry.type === "message" && entry.message.role === "assistant" ? entry.message : null; - if (candidate !== null && reply !== null) steerAnswers.add(candidate); + if (candidate !== null && reply !== null) keptAnswers.add(candidate); candidate = null; if (answering && startsResponse(entry)) answeringFrom = index + 1; if (entry.type === "message" && entry.message.role === "user") { @@ -1558,7 +1554,7 @@ function zenAnswerMessageIds( replies .filter( ({ message, index }) => - steerAnswers.has(message.id) || + keptAnswers.has(message.id) || (terminal.has(message.id) && index < answeringFrom && (answeringRunId === null || message.runId !== answeringRunId)), @@ -2409,8 +2405,10 @@ export function buildThreadFeed( const attemptId = resolveAttemptId(item); const cached = projectedEntriesCache.get(row); if (cached?.attemptId === attemptId) { - entries.push(cached.entry); - entryRows.push(index); + for (const entry of cached.entries) { + entries.push(entry); + entryRows.push(index); + } continue; } const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt); @@ -2426,24 +2424,7 @@ export function buildThreadFeed( runId: item.runId, render, }; - projectedEntriesCache.set(row, { attemptId, entry }); - entries.push(entry); - entryRows.push(index); - continue; - } - const app = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined; - if (app) { - const entry: RawThreadFeedEntry = { - type: "mcp-app", - id: `mcp-app:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`, - createdAt, - runId: item.runId, - sourceThreadId: row.sourceThreadId, - itemId: row.sourceItemId, - revision: turnItemDetailRevision(item), - app, - }; - projectedEntriesCache.set(row, { attemptId, entry }); + projectedEntriesCache.set(row, { attemptId, entries: [entry] }); entries.push(entry); entryRows.push(index); continue; @@ -2480,22 +2461,34 @@ export function buildThreadFeed( projectedItem: row, }, }; - projectedEntriesCache.set(row, { attemptId, entry }); + projectedEntriesCache.set(row, { attemptId, entries: [entry] }); entries.push(entry); entryRows.push(index); continue; } const activity = toFeedActivity(row, attemptId); - const entry: RawThreadFeedEntry = { - type: "activity", - id: activity.id, - createdAt, - runId: item.runId, - activity, - }; - projectedEntriesCache.set(row, { attemptId, entry }); - entries.push(entry); - entryRows.push(index); + const rowEntries: RawThreadFeedEntry[] = [ + { type: "activity", id: activity.id, createdAt, runId: item.runId, activity }, + ]; + // The card follows its tool activity: a feed restart resumes after a row's last entry. + const app = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined; + if (app) { + rowEntries.push({ + type: "mcp-app", + id: `mcp-app:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`, + createdAt, + runId: item.runId, + sourceThreadId: row.sourceThreadId, + itemId: row.sourceItemId, + revision: turnItemDetailRevision(item), + app, + }); + } + projectedEntriesCache.set(row, { attemptId, entries: rowEntries }); + for (const entry of rowEntries) { + entries.push(entry); + entryRows.push(index); + } } const retainedMessageIds = new Set([ ...foldedAnswerRunIdByMessageId.keys(), diff --git a/apps/mobile/src/native/nativeWebSocket.ios.test.ts b/apps/mobile/src/native/nativeWebSocket.ios.test.ts index 0a1a38850b554..8b2b128b5f7f8 100644 --- a/apps/mobile/src/native/nativeWebSocket.ios.test.ts +++ b/apps/mobile/src/native/nativeWebSocket.ios.test.ts @@ -126,6 +126,6 @@ describe("NativeWebSocket", () => { code: 1011, closeReason: "boom", }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/mobile/src/persistence/mobile-database.test.ts b/apps/mobile/src/persistence/mobile-database.test.ts index a30717f7e7cb4..a0b9985cf05ba 100644 --- a/apps/mobile/src/persistence/mobile-database.test.ts +++ b/apps/mobile/src/persistence/mobile-database.test.ts @@ -39,23 +39,21 @@ describe("offline pull request cache", () => { } it.effect("restores saved records and clears them with the environment", () => - Effect.scoped( - Effect.gen(function* () { - yield* Effect.promise(sqliteDatabase); - const database = yield* MobileDatabase.make; - yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}'); - yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other"); - expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual( - Option.some('{"entries":[]}'), - ); - yield* database.clearEnvironmentCache(environmentId); - expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe( - "None", - ); - expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe( - "Some", - ); - }), - ), + Effect.gen(function* () { + yield* Effect.promise(sqliteDatabase); + const database = yield* MobileDatabase.make; + yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}'); + yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other"); + expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual( + Option.some('{"entries":[]}'), + ); + yield* database.clearEnvironmentCache(environmentId); + expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe( + "None", + ); + expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe( + "Some", + ); + }), ); }); diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 852d96c608520..f29fbc8c119b4 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -11,7 +11,7 @@ import { PullRequestListFilters, PullRequestListState, type ProviderInstanceId, - type PullRequestMergeMethod, + PullRequestMergeMethod, type SidebarProjectGroupingMode, } from "@t3tools/contracts"; import { ToolCallVisibility } from "@t3tools/contracts/settings"; @@ -174,6 +174,7 @@ export class MobilePreferencesStore extends Context.Service< >()("@t3tools/mobile/persistence/mobile-preferences/MobilePreferencesStore") {} const isToolCallVisibility = Schema.is(ToolCallVisibility); +const isPullRequestMergeMethod = Schema.is(PullRequestMergeMethod); function sanitizePreferences(parsed: Preferences): Preferences { const preferences: { @@ -232,11 +233,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles; } - if ( - parsed.pullRequestMergeMethod === "squash" || - parsed.pullRequestMergeMethod === "merge" || - parsed.pullRequestMergeMethod === "rebase" - ) { + if (isPullRequestMergeMethod(parsed.pullRequestMergeMethod)) { preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod; } diff --git a/apps/mobile/src/state/queries.test.ts b/apps/mobile/src/state/queries.test.ts index 12f36dfe2e242..dba11b2e56ea7 100644 --- a/apps/mobile/src/state/queries.test.ts +++ b/apps/mobile/src/state/queries.test.ts @@ -1,8 +1,10 @@ +import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches"; import { expect, it } from "@effect/vitest"; it("keeps an older exact PR in the mobile menu ahead of twenty newer substring matches", () => { const exact = { + host: "github.com", number: 42, projectId: "project", repository: "example/repo", @@ -14,6 +16,7 @@ it("keeps an older exact PR in the mobile menu ahead of twenty newer substring m updatedAt: "2026-01-01", })); const matches = filterComposerPullRequestMatches({ + keyOf: threadPullRequestKeyOf, entries: [exact, ...recent, exact], projectId: exact.projectId, repository: exact.repository, diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index 837d77ce851cf..a4cdbc6244204 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -1,3 +1,7 @@ +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "@t3tools/client-runtime/thread-pull-requests"; import { composerPullRequestsFromLinks, filterComposerPullRequestMatches, @@ -148,11 +152,16 @@ export function useComposerPullRequestSearch(input: { }) : null, ); + // Only the host: the URL's full repository path would not match the project's selector. + const exactEntry = exact.data + ? { ...exact.data, host: legacyThreadPullRequestKey(exact.data).host } + : null; const entries = (() => { if (input.query === null || input.projectId === null || input.repository === null) return []; if (/^\d*$/.test(input.query)) { return filterComposerPullRequestMatches({ - entries: ready ? [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])] : [], + keyOf: threadPullRequestKeyOf, + entries: ready ? [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])] : [], linked, projectId: input.projectId, repository: input.repository, @@ -162,6 +171,7 @@ export function useComposerPullRequestSearch(input: { } if (!ready) { return withLinkedComposerPullRequestsFirst({ + keyOf: threadPullRequestKeyOf, matches: [], linked, query: input.query, @@ -169,7 +179,7 @@ export function useComposerPullRequestSearch(input: { }); } const words = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean); - const found = [...(exact.data ? [exact.data] : []), ...(list.data?.entries ?? [])].filter( + const found = [...(exactEntry ? [exactEntry] : []), ...(list.data?.entries ?? [])].filter( (entry) => entry.projectId === input.projectId && entry.repository.toLowerCase() === input.repository?.toLowerCase() && @@ -177,9 +187,13 @@ export function useComposerPullRequestSearch(input: { `${entry.title} ${entry.headBranch} ${entry.baseBranch}`.toLowerCase().includes(word), ), ); - const unique = new Map(); - for (const entry of found) if (!unique.has(entry.number)) unique.set(entry.number, entry); + const unique = new Map(); + for (const entry of found) { + const key = threadPullRequestKeyOf(entry); + if (!unique.has(key)) unique.set(key, entry); + } return withLinkedComposerPullRequestsFirst({ + keyOf: threadPullRequestKeyOf, matches: [...unique.values()].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt), ), diff --git a/apps/mobile/src/state/use-composer-attachment-actions.ts b/apps/mobile/src/state/use-composer-attachment-actions.ts index d4fefec5361f4..eeb8742010858 100644 --- a/apps/mobile/src/state/use-composer-attachment-actions.ts +++ b/apps/mobile/src/state/use-composer-attachment-actions.ts @@ -101,11 +101,15 @@ export function useComposerAttachmentActions(props: { const insertion = captureComposerDraftInsertion(key); await withDraftOperation(key, async (signal) => { try { - const images = await convertPastedImagesToAttachments({ + const result = await convertPastedImagesToAttachments({ uris, existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion), }); - report("Could not paste images", null, await append(key, signal, images, insertion)); + report( + "Could not paste images", + result.error, + await append(key, signal, result.attachments, insertion), + ); } catch (error) { Dialog.alert( "Could not paste images", diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index f7fe9ebbcf57c..f25037f40f0b4 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -1901,7 +1901,7 @@ describe("mobile composer drafts", () => { expect(getComposerDraftSnapshot(second).text).toBe("second idea"); }); - it("retargets a new-task draft to another project without losing its text", () => { + it("retargets a new-task draft to another project, keeping only a pull request workspace", () => { const from = { environmentId: EnvironmentId.make("environment-1"), projectId: ProjectId.make("project-1"), @@ -1922,7 +1922,7 @@ describe("mobile composer drafts", () => { }); const createdAt = getComposerDraftSnapshot(key).project?.createdAt; - retargetNewTaskDraft(key, to); + retargetNewTaskDraft(key, to, { keepPullRequestWorkspace: true }); const moved = getComposerDraftSnapshot(key); expect(moved.text).toBe("moving house"); @@ -1932,6 +1932,22 @@ describe("mobile composer drafts", () => { expect(moved.project).toEqual({ ...to, createdAt }); expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), from)).toEqual([]); expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), to)).toEqual([key]); + + const pullRequestSelection = { + mode: "worktree" as const, + branch: "feature/pr-head", + worktreePath: "/old-machine/worktrees/pr-42", + startFromOrigin: false, + pullRequestReference: "https://github.com/acme/repo/pull/42", + }; + updateComposerDraftSettings(key, { workspaceSelection: pullRequestSelection }); + retargetNewTaskDraft(key, from, { keepPullRequestWorkspace: true }); + expect(getComposerDraftSnapshot(key).workspaceSelection).toEqual({ + ...pullRequestSelection, + worktreePath: null, + }); + retargetNewTaskDraft(key, to); + expect(getComposerDraftSnapshot(key).workspaceSelection).toBeUndefined(); }); it("retargets a saved new-task draft only after drafts load", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 2e4e53ef6dd45..7fb44be817f32 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1965,6 +1965,7 @@ export function createNewTaskDraft(project: { export function retargetNewTaskDraft( draftKey: string, project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + options?: { readonly keepPullRequestWorkspace?: boolean }, ): void { updateComposerDrafts((current) => { const existing = current[draftKey]; @@ -1976,7 +1977,12 @@ export function retargetNewTaskDraft( ) { return current; } - const { workspaceSelection: _workspaceSelection, ...retained } = normalizeDraft(existing); + const { workspaceSelection, ...retained } = normalizeDraft(existing); + // The PR checkout is recreated on the target machine, so only the old local path is dropped. + const keptWorkspaceSelection = + options?.keepPullRequestWorkspace && workspaceSelection?.pullRequestReference !== undefined + ? { ...workspaceSelection, worktreePath: null } + : undefined; // Keep bytes across environment moves but drop server-specific upload stamps. const attachments = retained.attachments.map((attachment) => attachment.uploadEnvironmentId !== undefined && @@ -1988,6 +1994,7 @@ export function retargetNewTaskDraft( ...current, [draftKey]: { ...retained, + ...(keptWorkspaceSelection ? { workspaceSelection: keptWorkspaceSelection } : {}), attachments, project: { environmentId: project.environmentId, diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index c75456461bf64..a1488220d6952 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -100,7 +100,7 @@ const EMPTY_RUNTIME_STATE_ATOM = Atom.make(null) Atom.withLabel("mobile:environment-runtime-state:empty"), ); -const savedConnectionsByIdAtom = Atom.make((get) => { +export const savedConnectionsByIdAtom = Atom.make((get) => { const catalog = get(environmentCatalog.catalogValueAtom); return Object.fromEntries( [...catalog.entries.keys()].flatMap((environmentId) => { diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 56fafe6d676cc..2b688fee30ad2 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -10,6 +10,7 @@ const reactTests = [ "src/state/use-thread-pr.demand.test.tsx", "src/features/threads/git/GitBranchesSheet.occupancy.test.tsx", "src/features/files/useFileTreeEntries.test.tsx", + "src/features/files/thread-file-navigator-pane.test.tsx", "src/features/files/source-file-document.test.ts", "src/features/projects/AddProjectScreen.test.ts", "src/lib/useMediaVideoPlayback.test.tsx", diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index 91045459d281e..c81b01b0fe604 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -9,9 +9,9 @@ import { runMigrations } from "../src/persistence/Migrations.ts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { runMigrateDevDb } from "./migrate-dev-db.ts"; -const withDatabase = ( +const withDatabase = ( databasePath: string, - effect: Effect.Effect, + effect: Effect.Effect, ) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath }))); const insertPeerLink = (sql: SqlClient.SqlClient) => sql`INSERT INTO peer_environment_links @@ -111,9 +111,14 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio (run_id, thread_id, ordinal, provider, status, requested_at, payload_json) VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`; yield* sql`INSERT INTO orchestration_events - (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json) - VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`; + (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version) + VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}', 2)`; } + // A V1 thread the server already imported must not trip the legacy guard. + yield* sql`INSERT INTO projection_threads + (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at) + VALUES ('stopped-thread', 'project-kept', 'stopped-thread', + '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', '2026-08-01', '2026-08-01')`; yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions (provider_session_id, thread_id, provider, status, updated_at, payload_json) VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`; @@ -324,6 +329,61 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { }), ); + // The server imports V1 threads at boot, not in a migration, so a source can + // reach the V2 schema with its legacy threads still unimported. + it.effect.each([ + { name: "a pre-V2 source", migrateToLatest: false }, + { name: "a V2 source whose legacy threads were never imported", migrateToLatest: true }, + ])("refuses $name", ({ migrateToLatest }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-data-" }); + const destDir = yield* fs.makeTempDirectoryScoped({ + prefix: "migrate-dev-db-v1-data-dest-", + }); + const stateDir = path.join(sourceDir, "userdata"); + const source = path.join(stateDir, "statev2.sqlite"); + yield* fs.makeDirectory(stateDir, { recursive: true }); + yield* withDatabase( + source, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 54 }); + yield* sql`INSERT INTO projection_projects + (project_id, title, workspace_root, scripts_json, created_at, updated_at) + VALUES ('project-legacy', 'Legacy', '/tmp/legacy', '[]', '2026-08-01', '2026-08-01')`; + yield* sql`INSERT INTO projection_threads + (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at) + VALUES ('thread-legacy', 'project-legacy', 'Legacy thread', + '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', '2026-08-01', '2026-08-01')`; + if (migrateToLatest) yield* runMigrations(); + }), + ); + + // A live destination connection keeps uncheckpointed rows in the WAL; + // the rejected run must leave those bytes alone. + const destination = yield* createFixtureSource(destDir); + yield* withDatabase( + destination, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared; + yield* sql`UPDATE projection_projects SET title = 'Edited' WHERE project_id = 'project-kept'`; + const walBefore = yield* fs.readFile(`${destination}-wal`); + assert.isAbove(walBefore.length, 0); + + const error = yield* runMigrateDevDb( + { baseDir: destDir, source, projects: 5, threadsPerProject: 10 }, + { sharedHome: sourceDir }, + ).pipe(Effect.flip); + assert.equal(error._tag, "MigrateDevDbLegacySourceError"); + assert.deepStrictEqual(yield* fs.readFile(`${destination}-wal`), walBefore); + }), + ); + }), + ); + it.effect("seeds from a source that recorded another migration below V2", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index 211895c9b44fa..b44e7c52ea14f 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -60,6 +60,18 @@ export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedError()( + "MigrateDevDbLegacySourceError", + { + sourcePath: Schema.String, + legacyThreads: Schema.Number, + }, +) { + override get message(): string { + return `Source database '${this.sourcePath}' holds ${this.legacyThreads} legacy threads the server has not imported into V2 yet, which this command cannot carry over. Start a server once on a T3 home holding a copy of it so it imports them, then pass the userdata/statev2.sqlite that server leaves behind as --source.`; + } +} + export class MigrateDevDbServerRunningError extends Schema.TaggedError()( "MigrateDevDbServerRunningError", { @@ -210,47 +222,71 @@ const rootIsVisible = (sql: SqlClient.SqlClient) => sql` AND json_extract(root.payload_json, '$.deletedAt') IS NULL AND json_extract(root.payload_json, '$.archivedAt') IS NULL`; -// A single read transaction keeps the copy consistent with concurrent server writes. +// One read transaction keeps the copy, and its legacy-thread guard, consistent with concurrent +// server writes. The server imports V1 threads at boot, and the copy keeps only threads with V2 +// rows, so unimported ones would vanish silently (see LegacyV1ThreadImporter.pendingThreadCount). const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: string) { const sql = yield* SqlClient.SqlClient; yield* sql`ATTACH DATABASE ${`${NodeURL.pathToFileURL(sourcePath).href}?mode=ro`} AS src`; - const schema = yield* sql<{ type: string; name: string; sql: string }>` - SELECT type, name, sql FROM src.sqlite_master - WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'`; - const threadColumns = yield* sql<{ name: string; notnull: number }>` - SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c - WHERE m.type = 'table' AND c.name = 'thread_id'`; - const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0])); - // FTS5 makes its own shadow tables and contentless rows cannot be copied: - // create the virtual table, skip its shadow tables and rows, and rebuild the - // index once the messages and triggers are in. - const virtualTables = schema - .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql)) - .map((entry) => entry.name); - const isShadowTable = (name: string) => - virtualTables.some((virtual) => - FTS5_SHADOW_SUFFIXES.some((suffix) => name === `${virtual}${suffix}`), - ); - const tables = schema.filter((entry) => entry.type === "table" && !isShadowTable(entry.name)); - const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads"); - // A row that points into a cleared table cannot be copied, so whatever references one is - // cleared with it, however far down the chain a newer migration added it. - const references = yield* sql<{ name: string; parent: string }>` - SELECT m.name, f."table" AS parent FROM src.sqlite_master m, pragma_foreign_key_list(m.name, 'src') f - WHERE m.type = 'table'`; - const cleared = new Set(CLEARED_TABLES); - for (let grew = true; grew;) { - grew = false; - for (const { name, parent } of references) { - if (cleared.has(parent) && !cleared.has(name)) { - cleared.add(name); - grew = true; - } - } - } yield* sql.withTransaction( Effect.gen(function* () { + const schema = yield* sql<{ type: string; name: string; sql: string }>` + SELECT type, name, sql FROM src.sqlite_master + WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'`; + const threadColumns = yield* sql<{ name: string; notnull: number }>` + SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c + WHERE m.type = 'table' AND c.name = 'thread_id'`; + const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0])); + // FTS5 makes its own shadow tables and contentless rows cannot be copied: + // create the virtual table, skip its shadow tables and rows, and rebuild the + // index once the messages and triggers are in. + const virtualTables = schema + .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql)) + .map((entry) => entry.name); + const isShadowTable = (name: string) => + virtualTables.some((virtual) => + FTS5_SHADOW_SUFFIXES.some((suffix) => name === `${virtual}${suffix}`), + ); + const tables = schema.filter((entry) => entry.type === "table" && !isShadowTable(entry.name)); + const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads"); + // A row that points into a cleared table cannot be copied, so whatever references one is + // cleared with it, however far down the chain a newer migration added it. + const references = yield* sql<{ name: string; parent: string }>` + SELECT m.name, f."table" AS parent FROM src.sqlite_master m, pragma_foreign_key_list(m.name, 'src') f + WHERE m.type = 'table'`; + const cleared = new Set(CLEARED_TABLES); + for (let grew = true; grew;) { + grew = false; + for (const { name, parent } of references) { + if (cleared.has(parent) && !cleared.has(name)) { + cleared.add(name); + grew = true; + } + } + } + + if (tables.some((table) => table.name === "projection_threads")) { + // The V2 tables, application_event_version, and the partial index arrive in + // the same migration. Without the hint SQLite scans each thread's stream. + const [pending] = filtered + ? yield* sql<{ count: number }>` + SELECT COUNT(*) AS count FROM src.projection_threads AS thread + WHERE NOT EXISTS ( + SELECT 1 + FROM src.orchestration_events AS event INDEXED BY orchestration_events_v2_created_threads_idx + WHERE event.application_event_version = 2 + AND event.aggregate_kind = 'thread' + AND event.stream_id = thread.thread_id + AND event.event_type = 'thread.created' + )` + : yield* sql<{ count: number }>`SELECT COUNT(*) AS count FROM src.projection_threads`; + const legacyThreads = Number(pending?.count ?? 0); + if (legacyThreads > 0) { + return yield* new MigrateDevDbLegacySourceError({ sourcePath, legacyThreads }); + } + } + for (const table of tables) yield* sql.unsafe(table.sql).unprepared; if (filtered) { yield* sql`CREATE TEMP TABLE copied_threads (thread_id TEXT PRIMARY KEY)`; @@ -496,7 +532,6 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* ( } yield* fs.makeDirectory(stateDir, { recursive: true }); - yield* ensureNotInUse(databasePath); const wrapPhase = (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) => @@ -512,8 +547,15 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* ( yield* Console.log(`Copying visible threads from ${sourcePath} (read-only)...`); yield* copySourceSlice(sourcePath).pipe( Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })), - wrapPhase("snapshot", sourcePath), + Effect.catchTags({ + SqlError: (cause) => + Effect.fail( + new MigrateDevDbPhaseError({ phase: "snapshot", databasePath: sourcePath, cause }), + ), + }), ); + // Checkpoints the destination, so it runs after the copy's legacy guard. + yield* ensureNotInUse(databasePath); // Migrate first so prune queries can use columns missing from older sources. yield* Console.log("Running migrations on the snapshot..."); diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index d762a15a830f8..681af43bdf347 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1566,10 +1566,7 @@ describe("AssetAccess", () => { // A pull request's own repository wins over the checkout it is shown in. yield* sourceControlMediaResponse({ ...asset, repository: "enterprise/private" }, {}); expect(fetched.at(-1)?.repository).toBe("enterprise/private"); - }).pipe( - Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities)), - Effect.scoped, - ); + }).pipe(Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities))); }); it.effect("refuses media no host keeps behind a credential, without echoing the URL", () => diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index dee1d873cc29a..f6120ffe4d891 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -193,7 +193,7 @@ const authorizeParams = (clientId: string, redirect = "http://localhost:51234/ca resource: `${ORIGIN}/mcp`, }); -it.live("derives discovery metadata from the origin the client reached", () => +it.effect("derives discovery metadata from the origin the client reached", () => withRoutes((handler) => Effect.gen(function* () { const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp")); @@ -217,7 +217,7 @@ it.live("derives discovery metadata from the origin the client reached", () => ), ); -it.live("registers loopback and https clients and never redirects for an unverified client", () => +it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { for (const refused of [ @@ -663,7 +663,7 @@ it.live("an app approval code approves only an app sign-in, at its own level", ( ), ); -it.live( +it.effect( "sends an app sign-in on the linked tunnel to the hosted app, and a link to its own page", () => Effect.gen(function* () { diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 863a016836291..bb3fea5b28a3b 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -139,7 +139,7 @@ describe("RPC scope middleware", () => { requiredPermission: missing, }); expect(handled).toEqual([]); - }).pipe(Effect.scoped), + }), ); }); @@ -195,7 +195,7 @@ it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as : granted[method]({ cwd: "/repo" }).pipe(Stream.drain), ); expect(handled).toBe(1); - }).pipe(Effect.scoped), + }), ); describe("settings mutation authorization", () => { @@ -264,7 +264,7 @@ describe("settings mutation authorization", () => { }).pipe(Effect.flip), ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); expect(handled).toBe(2); - }).pipe(Effect.scoped), + }), ); it.effect("does not let a settings grant create or remove providers or secret providers", () => @@ -295,7 +295,7 @@ describe("settings mutation authorization", () => { }).pipe(Effect.flip), ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); expect(handled).toBe(false); - }).pipe(Effect.scoped), + }), ); }); @@ -333,7 +333,7 @@ it.effect("requires task permission before attaching a prepared worktree to a th }).pipe(Effect.flip), ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); expect(handled).toBe(false); - }).pipe(Effect.scoped), + }), ); describe("thread context authorization", () => { @@ -385,7 +385,7 @@ describe("thread context authorization", () => { reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }), ); expect(handled.at(-1)).toBe("allowed"); - }).pipe(Effect.scoped), + }), ); }); @@ -433,7 +433,7 @@ it.effect("separates host file URLs from readable attachment URLs", () => }); } expect(handled).toBe(2); - }).pipe(Effect.scoped), + }), ); it.effect("denies manual cleanup before the handler without settings permission", () => @@ -474,5 +474,5 @@ it.effect("denies manual cleanup before the handler without settings permission" requiredPermission: AuthSettingsWriteScope, }); expect(handled).toBe(false); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index d041219669ea1..b5ac2f3c9577c 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -143,6 +143,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope, [WS_METHODS.pullRequestsReportState]: AuthOrchestrationReadScope, [WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope, + [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: AuthOrchestrationReadScope, [WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope, [WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope, [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope, diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index aae4a4a38b662..7c516e97fa730 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -300,7 +300,7 @@ it.effect("shares the turn and full-thread diff budget across real Git batches", turnPatchSizes.reduce((sum, size) => sum + size, 0), 10_000_001, ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("truncates a storage-cut UTF-8 character without replacement text", () => { diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index 062405d533216..bf9543919de65 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -1,4 +1,5 @@ import { + CHECKPOINT_DIFF_TRUNCATED_MARKER, OrchestrationGetTurnDiffResult, type OrchestrationGetFullThreadDiffInput, type OrchestrationGetFullThreadDiffResult, @@ -28,7 +29,6 @@ import { isGitImport, parseTurnDiffFilesFromNumstat, type TurnDiffFileSummary } // Windows limits a command line to 32,767 characters. Leave room for the rest of git's arguments. const MAX_PATHSPEC_CHARS = 24_000; -const DIFF_TRUNCATED_MARKER = "\n\n[truncated]"; function batchFilePaths(files: ReadonlyArray) { const batches: string[][] = []; @@ -243,10 +243,11 @@ export const make = Effect.gen(function* () { new TextDecoder().decode( Buffer.from(diff).subarray( 0, - CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(DIFF_TRUNCATED_MARKER), + CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - + Buffer.byteLength(CHECKPOINT_DIFF_TRUNCATED_MARKER), ), { stream: true }, - ) + DIFF_TRUNCATED_MARKER; + ) + CHECKPOINT_DIFF_TRUNCATED_MARKER; break; } remainingBytes -= patchBytes; diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index 51ce21339e8b0..7d7e35b0bea20 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -104,7 +104,7 @@ const environmentLinkCommand = Command.make("link", { ), }).pipe( Command.withDescription( - "Link another T3 Code environment, so agents here can work there. It shows up there under Settings → Connections, where it can be revoked.", + "Link another T3 Code environment, so agents here can work there. It shows up there under Authorized clients in Settings → Sharing & access, where it can be revoked.", ), Command.withHandler((flags) => runWithPeerLinks(flags, (links) => @@ -145,7 +145,7 @@ const environmentUnlinkCommand = Command.make("unlink", { ), }).pipe( Command.withDescription( - "Forget a linked environment here. Revoke it in that environment's Connections to end its session there too.", + "Forget a linked environment here. Revoke it in that environment's Sharing & access to end its session there too.", ), Command.withHandler((flags) => runWithPeerLinks(flags, (links) => @@ -153,7 +153,7 @@ const environmentUnlinkCommand = Command.make("unlink", { const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId)); yield* Console.log( removed - ? `Forgot ${flags.environmentId}. Revoke it in that environment's Connections to end its session there.\n` + ? `Forgot ${flags.environmentId}. Revoke it in that environment's Sharing & access to end its session there.\n` : `No linked environment ${flags.environmentId}.\n`, ); }), diff --git a/apps/server/src/cli/install.test.ts b/apps/server/src/cli/install.test.ts index 36deef5df342f..80b3041d24e77 100644 --- a/apps/server/src/cli/install.test.ts +++ b/apps/server/src/cli/install.test.ts @@ -162,7 +162,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => { ), ).pipe(Effect.flip); assert.include(unrunnable.message, "has % or non-ASCII characters"); - }).pipe(Effect.scoped), + }), ); it.effect("asks npx users without a t3 command once per minor release and installs on yes", () => @@ -267,7 +267,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => { assert.isTrue(yield* Fiber.join(unanswered)); assert.isTrue(yield* fs.exists(declined)); assert.isFalse(yield* fs.exists(link)); - }).pipe(Effect.scoped), + }), ); it.effect("reads the terminal's foreground group from /proc and ps", () => diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 08e4024d5bfe0..4d41bf40f1a07 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -53,7 +53,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => { path: yield* pathWithT3, }), ).toBe('sudo env "PATH=$PATH" t3 browser setup'); - }).pipe(Effect.scoped), + }), ); it.effect("keeps the arguments, so root runs setup on the same T3 home", () => @@ -70,7 +70,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => { expect( yield* rootCommand({ node: "/opt/t3/t3", entry: "/opt/t3/t3", executable: true, args }), ).toBe("sudo /opt/t3/t3 browser setup --base-dir '/srv/t3 home'"); - }).pipe(Effect.scoped), + }), ); it.effect("names this install's launcher when t3 is not on PATH", () => @@ -143,7 +143,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => { expect( yield* rootCommand({ ...desktop, env: { T3CODE_CLI_PATH: path.join(home, "gone") } }), ).toBe('sudo env "PATH=$PATH" t3 browser setup'); - }).pipe(Effect.scoped), + }), ); }); @@ -184,7 +184,7 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { expect((yield* hostCommand("linux", { T3CODE_CLI_PATH: shim })).command).toMatch( / doctor --base-dir 'C:\\Users\\Jane Doe\\\.t3'$/, ); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 407905815f434..bca02daaf2916 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -191,7 +191,7 @@ it.effect.each(["snapshot", "mutation"] as const)( assert.equal(snapshotRequests, 2); assert.equal(mutations, 1); assert.deepEqual((yield* readProjects(baseDir)).projects, []); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("does not send a token to whatever took over a dead server's port", () => @@ -222,7 +222,7 @@ it.effect("does not send a token to whatever took over a dead server's port", () assert.equal(requests, 0); assert.equal((yield* readProjects(baseDir)).projects[0]?.workspaceRoot, workspaceRoot); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () { diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index 900c41e661740..7dd4e852adba8 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -115,6 +115,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands env: "T3CODE_HOST=::\n", expected: "T3CODE_HOST=::\n", }, + { + label: "a quoted multiline value", + installed: false, + env: 'CUSTOM="first\nT3CODE_LAN=example\nlast"\n', + expected: 'CUSTOM="first\nT3CODE_LAN=example\nlast"\nT3CODE_LAN=false\n', + }, ])("install keeps $label off the local network only when it is new", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index dedc095f62ffd..2a34eb09dd08e 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -47,14 +47,37 @@ export const upsertServiceEnv = ( entries: Readonly>, ): string => { const written = new Set(); - const lines = contents.split("\n").flatMap((line) => { - const key = SERVICE_ENV_KEY.exec(line)?.[1]; - if (key === undefined || !Object.hasOwn(entries, key)) return [line]; + const source = contents.split("\n"); + const lines: string[] = []; + for (let index = 0, offset = 0; index < source.length;) { + const line = source[index]!; + const match = SERVICE_ENV_KEY.exec(line); + let end = index + 1; + if (match !== null) { + // util.parseEnv lets a quoted value run to its closing quote across lines, + // skipping only spaces, tabs and CRs before the opening quote. + const rest = line.slice(match[0].length).replace(/^[ \t\r]+/u, ""); + const quote = rest[0]; + if ((quote === '"' || quote === "'" || quote === "`") && !rest.includes(quote, 1)) { + const closing = contents.indexOf(quote, offset + line.length); + if (closing !== -1) { + end += contents.slice(offset + line.length, closing).split("\n").length - 1; + } + } + } + const span = source.slice(index, end); + offset += span.reduce((length, part) => length + part.length + 1, 0); + index = end; + const key = match?.[1]; + if (key === undefined || !Object.hasOwn(entries, key)) { + lines.push(span.join("\n")); + continue; + } const value = entries[key]; - if (value === undefined || written.has(key)) return []; + if (value === undefined || written.has(key)) continue; written.add(key); - return [`${key}=${value}`]; - }); + lines.push(`${key}=${value}`); + } while (lines.at(-1) === "") lines.pop(); for (const [key, value] of Object.entries(entries)) { if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`); diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index c50a5a15aad40..3e1e37a274b4e 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -149,7 +149,7 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { ), [cmd], ); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); }); diff --git a/apps/server/src/cli/up.test.ts b/apps/server/src/cli/up.test.ts index f97a540570b6c..05d4185593a37 100644 --- a/apps/server/src/cli/up.test.ts +++ b/apps/server/src/cli/up.test.ts @@ -413,4 +413,18 @@ it("rewrites only the named service.env keys and keeps the user's lines", () => ["# my settings", "T3CODE_PORT=4000", "T3CODE_LAN=true", ""].join("\n"), ); expect(upsertServiceEnv("", { T3CODE_LAN: "false" })).toBe("T3CODE_LAN=false\n"); + expect( + upsertServiceEnv('T3CODE_LAN="a\nb"\nCUSTOM="x\nT3CODE_LAN=y"\nT3CODE_LAN=true\n', { + T3CODE_LAN: "false", + }), + ).toBe('T3CODE_LAN=false\nCUSTOM="x\nT3CODE_LAN=y"\n'); + expect( + upsertServiceEnv('T3CODE_LAN=\u00a0"unused\nCUSTOM=keep\nEND="\nT3CODE_LAN=true\n', { + T3CODE_LAN: "false", + }), + ).toBe('T3CODE_LAN=false\nCUSTOM=keep\nEND="\n'); + const long = `CUSTOM="${"\n".repeat(130_000)}"\n`; + expect(upsertServiceEnv(`${long}T3CODE_LAN=true\n`, { T3CODE_LAN: "false" })).toBe( + `${long}T3CODE_LAN=false\n`, + ); }); diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index 557dddef554a9..2fc2e29b6223c 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -219,7 +219,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher); assert.equal(yield* fs.readLink(launcher), newExe); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect.each([ @@ -285,7 +285,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { yield* fs.realPath(launcher), yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")), ); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); const launcherFixture = Effect.fnUntraced(function* () { @@ -316,7 +316,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { }); assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect("fails instead of repointing a launcher it cannot record", () => @@ -334,7 +334,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { assert.isTrue(Exit.isFailure(result)); assert.equal(yield* fs.readLink(launcher), oldExe); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect.each(["recording", "repointing"] as const)( @@ -370,7 +370,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { .split("\n") .includes(launcher); assert.isFalse(repointed && !recorded); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect("leaves a plain copy or a foreign symlink alone", () => @@ -403,7 +403,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { } assert.equal(yield* fs.readLink(foreign), elsewhere); assert.equal(yield* fs.readLink(otherLauncher), otherHome); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect("finds the launcher a bare command name resolved to on PATH", () => @@ -437,7 +437,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { assert.equal(bare, launcher); assert.equal(relative, launcher); assert.equal(absent, undefined); - }).pipe(Effect.scoped), + }), ); }); @@ -527,7 +527,6 @@ it.layer(NodeServices.layer)("t3 update with a background service", (it) => { `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`, ); }).pipe( - Effect.scoped, Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, { PATH: "" }), ), diff --git a/apps/server/src/cliCompileCache.test.ts b/apps/server/src/cliCompileCache.test.ts index b58e7969999d3..4c733df134f52 100644 --- a/apps/server/src/cliCompileCache.test.ts +++ b/apps/server/src/cliCompileCache.test.ts @@ -77,9 +77,14 @@ it.live("loads the CLI with its cache settings only when the command needs it", expect(launcherFlags.exitCode).toBe(1); expect(launcherFlags.stderr).toContain("LOADED_CLI_MAIN"); expect(launcherFlags.stderr).toContain("[service-launcher] T3CODE_HOME is required"); + const cacheDir = `${root}/cache/t3code/compile-cache`; + yield* fs.makeDirectory(`${cacheDir}/v24.0.0-x64-legacy-1000`, { recursive: true }); + yield* fs.writeFileString(`${cacheDir}/v24.0.0-x64-legacy-1000/0123abcd`, "stale"); + yield* fs.makeDirectory(`${cacheDir}/server`, { recursive: true }); const appImage = yield* run({ APPIMAGE: `${root}/T3Code.AppImage` }); expect(appImage.exitCode).toBe(0); expect(appImage.stderr).toContain("CACHE=disabled"); + expect((yield* fs.readDirectory(cacheDir)).toSorted()).toEqual(["server"]); const existing = yield* run({ NODE_COMPILE_CACHE: `${root}/explicit` }); expect(existing.exitCode).toBe(0); expect(existing.stderr.replaceAll("\\", "/")).toContain( diff --git a/apps/server/src/cliCompileCache.ts b/apps/server/src/cliCompileCache.ts index 4387de73ba4cf..9ae842afadd47 100644 --- a/apps/server/src/cliCompileCache.ts +++ b/apps/server/src/cliCompileCache.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -- Runs before the CLI's Effect runtime loads. +import * as NodeFS from "node:fs"; import * as NodeModule from "node:module"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; @@ -6,12 +7,22 @@ import * as NodeSea from "node:sea"; export function enableCliCompileCache(): void { try { - // AppImage paths change each launch; SEA has no separate modules to cache. - if (process.env.APPIMAGE || NodeSea.isSea()) return; + // SEA has no separate modules to cache. + if (NodeSea.isSea()) return; const cacheRoot = process.env.XDG_CACHE_HOME || // oxlint-disable-next-line t3code/no-global-process-runtime -- Runs before the CLI's Effect runtime loads. (process.platform === "linux" ? NodePath.join(NodeOS.homedir(), ".cache") : NodeOS.tmpdir()); - NodeModule.enableCompileCache(NodePath.join(cacheRoot, "t3code", "compile-cache")); + const directory = NodePath.join(cacheRoot, "t3code", "compile-cache"); + if (process.env.APPIMAGE) { + // AppImage paths change each launch. Older shims cached anyway, filling Node's engine folders. + for (const entry of NodeFS.readdirSync(directory, { withFileTypes: true })) { + if (entry.isDirectory() && /^v\d/.test(entry.name)) { + NodeFS.rmSync(NodePath.join(directory, entry.name), { recursive: true, force: true }); + } + } + return; + } + NodeModule.enableCompileCache(directory); } catch {} } diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index c9f7d1a77c3da..cd4921ac452bb 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -119,7 +119,7 @@ it("protects the server unit from agents under CPU and memory pressure", () => { }); it.each([ - ["a unit", '/home/theo/T3 "Data"/100%\\x', BootService.renderBootServiceUnit], + ["a unit", "/home/theo/T3 Data/100%$x", BootService.renderBootServiceUnit], [ "a plist", "/Users/theo/a&b ", @@ -141,6 +141,41 @@ it.each([ ).toBe(program); }); +// systemd rejects a unit whose executable has a control character, quote or backslash, even quoted. +it.each([ + ["a double quote", '/home/theo/T3 "Data"'], + ["a single quote", "/home/theo/Theo's T3"], + ["a backslash", "/home/theo/T3\\Data"], + ["a newline", "/home/theo/T3\nData"], +])("renders a loadable unit, or refuses, for a T3 home with %s", (_, baseDir) => { + let unit: string; + try { + unit = BootService.renderBootServiceUnit({ + program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"], + baseDir, + logPath: `${baseDir}/userdata/logs/boot-service.log`, + unitPath: "/home/theo/.config/systemd/user/t3code.service", + }); + } catch { + return; + } + for (const line of unit.split("\n")) { + expect(line === "" || line.startsWith("[") || line.includes("=")).toBe(true); + } + const execStart = unit.split("\n").find((line) => line.startsWith("ExecStart=")); + const executable = execStart + ?.slice("ExecStart=".length) + .match(/^"((?:\\.|[^"\\])*)"|^(\S+)/) + ?.slice(1) + .find((group) => group !== undefined) + ?.replace(/\\(.)/g, "$1"); + expect(executable).toBeDefined(); + const unsafe = [...(executable ?? "")].filter( + (char) => char.charCodeAt(0) < 0x20 || `"'\\`.includes(char), + ); + expect(unsafe).toEqual([]); +}); + const macInstallerPath = "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin"; @@ -593,7 +628,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => { "preserves the custom install bin directory in the installed service on %s", (platform) => Effect.gen(function* () { - const installBinDir = '/custom/T3 & <100%>/"quoted"\\bin'; + const installBinDir = '/custom/T3\t& <100%>/"quoted"\\bin'; const { service, makeService, fs } = yield* makeHarness( platform, "", @@ -605,8 +640,8 @@ it.layer(NodeServices.layer)("boot service install", (it) => { const unit = yield* fs.readFileString(plan.unitPath); expect(unit).toContain( platform === "linux" - ? 'Environment=T3CODE_INSTALL_BIN_DIR="/custom/T3 & <100%%>/\\"quoted\\"\\\\bin"' - : 'T3CODE_INSTALL_BIN_DIR\n /custom/T3 & <100%>/"quoted"\\bin', + ? 'Environment=T3CODE_INSTALL_BIN_DIR="/custom/T3\t& <100%%>/\\"quoted\\"\\\\bin"' + : 'T3CODE_INSTALL_BIN_DIR\n /custom/T3\t& <100%>/"quoted"\\bin', ); expect((yield* service.status).current).toBe(true); @@ -1185,6 +1220,14 @@ process.disconnect(); expect(yield* fs.readFileString(plan.unitPath)).toBe(unit); expect(commands).toEqual([]); expect((yield* other.status).otherBaseDir).toBe(baseDir); + + const quoted = yield* makeService(undefined, "1.2.3", path.join(otherHome, 'T3 "Data"')); + commands.length = 0; + const unloadable = yield* quoted.install().pipe(Effect.flip); + expect(unloadable._tag).toBe("BootServiceBaseDirUnsupportedError"); + expect(CliError.getUserMessage(unloadable)).toBe(unloadable.message); + expect(yield* fs.readFileString(plan.unitPath)).toBe(unit); + expect(commands).toEqual([]); }), ); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 1f5bc0c0d355d..bea0f8de6ae88 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -45,6 +45,7 @@ import { parseServiceState, serviceStateActiveVersion, serviceStateHasPendingUpdate, + systemdUnitDirectoryOf, type ServiceState, } from "./serviceProtocol.ts"; @@ -90,8 +91,16 @@ export interface BootServicePlan { readonly handedOff?: boolean; } +// systemd refuses an executable with a quote, backslash or control character even when +// quoted. The executable lives under the T3 home, so this also catches a home with a newline. +const systemdUnsafeValue = (plan: BootServicePlan) => + /[\x00-\x1f\x7f"'\\]/.test(plan.program[0] ?? ""); + /** Service units cannot rely on the user's shell or PATH. */ export function renderBootServiceUnit(plan: BootServicePlan): string { + if (systemdUnsafeValue(plan)) { + throw new BootServiceBaseDirUnsupportedError({ baseDir: plan.baseDir }); + } // The user manager has no reliable network-online target; server networking retries itself. return [ "[Unit]", @@ -550,7 +559,7 @@ const decodeSystemdUnitPaths = Schema.decodeUnknownEffect( // The manager may not share the installer's environment; JSON preserves spaces in its paths. const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")( - function* (runner: ProcessRunner.ProcessRunner["Service"], path: Path.Path) { + function* (runner: ProcessRunner.ProcessRunner["Service"]) { const result = yield* runner.run({ command: "busctl", args: [ @@ -566,14 +575,7 @@ const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit }); if (result.code !== 0) return undefined; const { data } = yield* decodeSystemdUnitPaths(result.stdout); - // The persistent control directory identifies the manager's config root despite UnitPath overrides. - const controlDirectory = data.find( - (directory) => - path.isAbsolute(directory) && - directory.endsWith("/systemd/user.control") && - data.includes(directory.slice(0, -".control".length)), - ); - return controlDirectory?.slice(0, -".control".length); + return systemdUnitDirectoryOf(data); }, Effect.orElseSucceed(() => undefined), ); @@ -591,7 +593,7 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun } if (platform !== "linux") return undefined; const unitDir = - (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ?? + (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner)) ?? defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? ""); return path.join(unitDir, BOOT_SERVICE_UNIT_FILE); }); @@ -711,8 +713,22 @@ export class BootServiceOtherBaseDirError extends Schema.TaggedError()( + "BootServiceBaseDirUnsupportedError", + { baseDir: Schema.String }, +) { + override get message(): string { + return `systemd cannot run T3 Code from ${JSON.stringify(this.baseDir)}: the path contains a quote, backslash or control character. Choose another T3 home with --base-dir.`; + } + + override get [CliError.userMessage]() { + return this.message; + } +} + export type BootServiceError = | BootServiceUnsupportedError + | BootServiceBaseDirUnsupportedError | BootServiceOtherBaseDirError | BootServiceCommandError | BootServiceInstallError @@ -972,8 +988,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { }; return { manager, unitPath, plan }; }; - let systemdUnitDir = - platform === "linux" ? yield* readSystemdUnitDirectory(runner, path) : undefined; + let systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory(runner) : undefined; let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); @@ -1181,6 +1196,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { readonly start?: boolean; }) { let manager = yield* requireManager; + if (manager.kind === "systemd" && systemdUnsafeValue(plan)) { + return yield* new BootServiceBaseDirUnsupportedError({ baseDir: input.baseDir }); + } // The unit is per user. Rewriting one that serves another home moves the // service onto this home's data, which looks like every thread vanished. const refuseOtherBaseDir = Effect.gen(function* () { @@ -1205,7 +1223,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Without a session the manager was unreachable at construction, and the one lingering // started may use another config root than this shell's XDG_CONFIG_HOME. if (systemdUnitDir === undefined) { - systemdUnitDir = yield* readSystemdUnitDirectory(runner, path); + systemdUnitDir = yield* readSystemdUnitDirectory(runner); ({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir)); manager = yield* requireManager; yield* refuseOtherBaseDir; @@ -1544,6 +1562,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { problems, current: problems.length === 0 && + !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 2c8dc31da24f6..f8de584ff2c8b 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -238,7 +238,7 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(installed), exe("2.0.0")); assert.equal(yield* fs.readLink(onPath), exe("2.0.0")); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () => @@ -292,7 +292,7 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.include(JSON.stringify(warnings), installed); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); assert.equal(yield* fs.readLink(onPath), exe("2.0.0")); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () => @@ -321,6 +321,6 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readFileString(installed), "user-owned file"); assert.equal(yield* fs.readLink(onPath), foreign); - }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); }); diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.ts index f3264b841c516..c0a43bfe23e16 100644 --- a/apps/server/src/cloud/serviceProtocol.ts +++ b/apps/server/src/cloud/serviceProtocol.ts @@ -63,6 +63,20 @@ export function serviceUnitBaseDirOf(contents: string): string | undefined { return task === undefined ? undefined : unquoteWindowsArgument(task); } +/** + * The user unit directory a systemd manager reads, from its UnitPath property. The persistent + * control directory identifies the manager's config root despite UnitPath overrides. + */ +export function systemdUnitDirectoryOf(unitPath: ReadonlyArray): string | undefined { + const controlDirectory = unitPath.find( + (directory) => + directory.startsWith("/") && + directory.endsWith("/systemd/user.control") && + unitPath.includes(directory.slice(0, -".control".length)), + ); + return controlDirectory?.slice(0, -".control".length); +} + /** The file systemd or launchd appends the service's output to. */ export function serviceUnitLogPathOf(contents: string): string | undefined { const systemd = /^StandardOutput=append:(.*)$/m.exec(contents)?.[1]; diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index f2e0bcdf0c725..e196b4cb7c3b4 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -379,7 +379,7 @@ describe("device setup consent", () => { status: "failed", detail: startupError.message, }); - }).pipe(Effect.scoped), + }), ); it.effect("names the missing npm in the host status when device support cannot install", () => @@ -473,7 +473,7 @@ describe("device setup consent", () => { detail: expected, }); } - }).pipe(Effect.scoped), + }), ); it.effect("listing and provider startup do not start helpers before consent", () => @@ -485,7 +485,7 @@ describe("device setup consent", () => { expect(readiness._tag).toBe("Failure"); expect(starts).toEqual([]); expect(requests).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -505,7 +505,7 @@ describe("device setup consent", () => { expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false); expect(yield* service.readinessIfSupported()).toBeNull(); expect(starts).toEqual(["start", "stop"]); - }).pipe(Effect.scoped), + }), ); it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () => @@ -522,7 +522,7 @@ describe("device setup consent", () => { const state = yield* service.state; expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]); expect(state.bootingDevices).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect("blocks only emulator video until ffmpeg is usable, then allows retry", () => @@ -604,7 +604,7 @@ describe("device setup consent", () => { const emulator = yield* openEmulator; expect(emulator.deviceId).toBe("emulator-5554"); expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1); - }).pipe(Effect.scoped), + }), ); it.effect("opens emulators on hosts that route their own streams without ffmpeg", () => @@ -627,7 +627,7 @@ describe("device setup consent", () => { }); expect(session.deviceId).toBe("emulator-5554"); expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1); - }).pipe(Effect.scoped), + }), ); it.effect("installs agent support only after the separate agent permission", () => @@ -646,7 +646,7 @@ describe("device setup consent", () => { expect(agentStops).toEqual(["stop"]); expect((yield* service.state).onboardingCompleted).toBe(true); expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true); - }).pipe(Effect.scoped), + }), ); }); @@ -726,7 +726,6 @@ it.effect.each([1, 9009])( NetService.layer, ).pipe(Layer.provideMerge(NodeServices.layer)), ), - Effect.scoped, ), ); @@ -753,7 +752,7 @@ it.effect("publishes boot progress and does not restore sessions after support i expect(state.devices).toEqual([]); expect(state.sessions).toEqual([]); expect(state.bootingDevices).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -783,7 +782,7 @@ it.effect.each([ endDevice(); yield* service.list; expect((yield* service.state).sessions).toHaveLength(kept); - }).pipe(Effect.scoped), + }), ); describe("device discovery after server restart", () => { @@ -796,7 +795,7 @@ describe("device discovery after server restart", () => { expect(capture.device.id).toBe("Pixel_API_35"); expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]); expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true); - }).pipe(Effect.scoped), + }), ); }); @@ -817,7 +816,7 @@ it.effect("keeps other discovery warnings and clears them when only a deleted pl const refreshed = yield* service.list; expect(refreshed.hostStatusDetail).toBeUndefined(); expect(refreshed.hostStatuses.local?.detail).toBeUndefined(); - }).pipe(Effect.scoped), + }), ); it.effect("hides Android discovery failures when the host has no Android SDK", () => @@ -831,7 +830,7 @@ it.effect("hides Android discovery failures when the host has no Android SDK", ( yield* Ref.set(androidAvailable, true); const withSdk = yield* service.list; expect(withSdk.hostStatusDetail).toBe(`${avdmanagerFailure.message}\niOS discovery failed.`); - }).pipe(Effect.scoped), + }), ); // The hub reports `error` as a util.inspect of Node's exec error. @@ -882,7 +881,7 @@ it.effect("keeps the cause from the hub's error in discovery warnings, without t ); expect(state.hostStatusDetail).not.toContain(" at "); expect(state.hostStatusDetail).not.toContain("stderr:"); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -916,7 +915,7 @@ it.effect( const recovered = yield* service.list; expect(recovered.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]); expect(recovered.hostStatuses.local).toEqual({ status: "ready" }); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -955,7 +954,7 @@ it.effect.each([ detail: "The device hub did not answer within 40 seconds.", incompletePlatforms, }); - }).pipe(Effect.scoped), + }), ); it.effect("does not open a retained pre-boot entry when the post-boot listing is incomplete", () => @@ -977,7 +976,7 @@ it.effect("does not open a retained pre-boot entry when the post-boot listing is yield* TestClock.adjust("40 seconds"); expect((yield* Fiber.join(opening))._tag).toBe("DeviceNotFoundError"); expect((yield* android.service.state).sessions).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -1012,7 +1011,7 @@ it.effect.each([ expect(error.message).toContain(message); expect(error.message).toContain(diagnostic); expect((yield* service.state).bootingDevices).toEqual([]); - }).pipe(Effect.scoped), + }), ); // regression: #22012 report Android emulator boot failures @@ -1040,7 +1039,7 @@ it.effect("includes nested hub boot diagnostics and bounds them to 2,000 charact const roundTrip = decodeBootError(encodeBootError(error)); expect(roundTrip.message).toBe(error.message); expect((yield* service.state).bootingDevices).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect("keeps shutdown successful when subsequent discovery fails", () => @@ -1057,7 +1056,7 @@ it.effect("keeps shutdown successful when subsequent discovery fails", () => const state = yield* service.state; expect(state.sessions).toEqual([]); expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false); - }).pipe(Effect.scoped), + }), ); it.effect.each(["shutdown", "close"] as const)( @@ -1239,7 +1238,7 @@ it.effect.each(["shutdown", "close"] as const)( yield* Fiber.join(binding); yield* Fiber.await(retiring); expect(launchers).toEqual(new Set()); - }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); it.effect("leaves a session its host leases to every thread open when one thread closes", () => @@ -1335,7 +1334,6 @@ it.effect("leaves a session its host leases to every thread open when one thread Effect.provide( ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }), ), - Effect.scoped, ), ); @@ -1441,7 +1439,7 @@ it.effect.each([ (yield* service.state).devices.find((device) => device.id === deviceId)?.booted, ).toBe(true); } - }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( @@ -1527,7 +1525,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( ]); expect(recovered.hostStatuses[hostId]).toEqual({ status: "ready" }); if (hostId === LOCAL_DEVICE_HOST_ID) expect(recovered.hostStatusDetail).toBeUndefined(); - }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); it.effect("retry keeps device and agent consent unchanged", () => @@ -1543,7 +1541,7 @@ it.effect("retry keeps device and agent consent unchanged", () => const before = agentStarts.length; yield* service.retryHost(LOCAL_DEVICE_HOST_ID); expect(agentStarts.length).toBe(before + 1); - }).pipe(Effect.scoped), + }), ); it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () => @@ -1555,7 +1553,7 @@ it.effect("failed read-only discovery preserves lifecycle status and installed i expect(state.hosts[0]?.hubInstalled).toBe(true); expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host"); expect(starts).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -1586,7 +1584,7 @@ it.effect( expect(requests).toEqual([]); yield* service.updateTool("hub"); expect(installed).toEqual(["agent", "hub"]); - }).pipe(Effect.scoped), + }), ); it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () => @@ -1619,7 +1617,7 @@ it.effect("failed manual installation leaves lifecycle state unchanged and can b expect(attempts).toBe(2); expect(starts).toEqual([]); expect(agentStarts).toEqual([]); - }).pipe(Effect.scoped), + }), ); it.effect("reconciles SSH host settings without publishing no-op changes", () => @@ -1798,7 +1796,6 @@ it.effect("a failed tool update reports npm's exit code but not its output", () NetService.layer, ).pipe(Layer.provideMerge(NodeServices.layer)), ), - Effect.scoped, ), ); @@ -2021,7 +2018,7 @@ describe("agent session release on close", () => { ) .filter((label, index, labels) => label !== labels[index - 1]); expect(published).toEqual(["none", "reopened"]); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index e133b4f9db36c..5f7cef54f5277 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "@effect/vitest"; import * as NodePath from "@effect/platform-node/NodePath"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -45,7 +47,8 @@ const agentFixture = Effect.fn("agentFixture")(function* ( const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" }); - const hub = { running: true, spawnFails: false }; + const hub = { running: true, spawnFails: false, cleanup: Effect.void }; + const daemonStopRequested = yield* Deferred.make>(); const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); const daemonHealthy = yield* Ref.make(true); const runs: Array = []; @@ -80,20 +83,22 @@ const agentFixture = Effect.fn("agentFixture")(function* ( description: "Hub entry missing", }), ) - : Effect.succeed( - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(123), - stdout: Stream.empty, - stderr: Stream.empty, - all: Stream.empty, - exitCode: Effect.never, - isRunning: Effect.sync(() => hub.running), - kill: () => Effect.void, - stdin: Sink.drain, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - unref: Effect.succeed(Effect.void), - }), + : Effect.addFinalizer(() => hub.cleanup).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.never, + isRunning: Effect.sync(() => hub.running), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), ), ), ), @@ -102,7 +107,9 @@ const agentFixture = Effect.fn("agentFixture")(function* ( runs.push(input); return input.args.includes("devices") ? startup(stateDir) - : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); + : input.args.includes("daemon") + ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0))) + : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); }, }), Effect.provideService( @@ -122,7 +129,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ), ); yield* host.ensureReady(() => Effect.void); - return { host, fs, baseDir, stateDir, hub, daemonHealthy, runs }; + return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs }; }); describe("AgentDevice startup", () => { @@ -353,6 +360,33 @@ describe("AgentDevice startup", () => { expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.effect("stops the agent daemon while the hub is still shutting down", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) => + fs + .writeFileString( + `${stateDir}/daemon.json`, + JSON.stringify({ httpPort: 12345, token: "test-token" }), + ) + .pipe(Effect.orDie, Effect.as(processOutput(0))), + ); + yield* host.ensureAgentReady(() => Effect.void); + const hubExited = yield* Deferred.make(); + hub.cleanup = Deferred.await(hubExited); + const stopping = yield* Effect.forkChild(host.stop); + expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([ + "daemon", + "stop", + "--state-dir", + stateDir, + ]); + yield* Deferred.succeed(hubExited, undefined); + yield* Fiber.join(stopping); + expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); const diagnose = ( diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index c5097509dcade..e657d0dcdfc13 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -870,9 +870,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)( Effect.gen(function* () { const running = yield* Ref.getAndSet(runningRef, null); - yield* stopHub(running?.hub); - yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore); - yield* stopAgentDeviceDaemon; + // Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon. + yield* Effect.all( + [ + stopHub(running?.hub).pipe( + Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)), + ), + stopAgentDeviceDaemon, + ], + { concurrency: "unbounded", discard: true }, + ); }), ); diff --git a/apps/server/src/device/SimlockDeviceHost.test.ts b/apps/server/src/device/SimlockDeviceHost.test.ts index 752a63c038b81..8726a7a7c03de 100644 --- a/apps/server/src/device/SimlockDeviceHost.test.ts +++ b/apps/server/src/device/SimlockDeviceHost.test.ts @@ -4,6 +4,7 @@ import { SecretProviderId, type SimlockDeviceHostConfig } from "@t3tools/contrac import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Clock from "effect/Clock"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; import * as Exit from "effect/Exit"; @@ -56,6 +57,8 @@ const fakePool = ( readonly entered: Deferred.Deferred; readonly proceed: Deferred.Deferred; }; + /** The gateway's `lease.maxTtlMs`: leases expire one TTL after their last renewal. */ + readonly maxTtlMs?: number; } = {}, ) => Effect.gen(function* () { @@ -66,8 +69,10 @@ const fakePool = ( let leases = 0; let renewStatus = 200; let catalog: unknown = CATALOG; + let leaseDeadline = Infinity; const http = HttpClient.make((request) => - Effect.sync(() => { + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; const url = new URL(request.url); requests.push(`${request.method} ${url.pathname}`); const json = (body: unknown, status = 200) => @@ -75,6 +80,17 @@ const fakePool = ( if (request.headers.authorization !== "Bearer agent-token") return json({ error: { code: "UNAUTHENTICATED", message: "Unknown bearer token" } }, 401); if (url.pathname === "/v1/catalog") return json(catalog); + if (url.pathname.endsWith("/renew") && options.maxTtlMs !== undefined) { + if (now >= leaseDeadline) return json({}, 404); + const body = + request.body._tag === "Uint8Array" + ? (JSON.parse(new TextDecoder().decode(request.body.body)) as { ttlMs?: number }) + : {}; + if ((body.ttlMs ?? 0) > options.maxTtlMs) + return json({ error: { code: "BAD_REQUEST", message: "ttlMs exceeds maxTtlMs" } }, 400); + leaseDeadline = now + (body.ttlMs ?? options.maxTtlMs); + return json({}); + } if (url.pathname.endsWith("/renew")) return json({}, renewStatus); if (request.method === "DELETE") return json({}, 202); return json({}, 404); @@ -114,6 +130,8 @@ const fakePool = ( path.join(dir, `${session}.json`), JSON.stringify({ leaseId: `lease-${++leases}` }), ); + if (options.maxTtlMs !== undefined) + leaseDeadline = (yield* Clock.currentTimeMillis) + options.maxTtlMs; } if (command === "screenshot") yield* fs.writeFile(args[1]!, new Uint8Array([1, 2, 3])); return { @@ -475,6 +493,21 @@ describe("Simlock device host", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); + it.effect("keeps a watched lease renewed when the gateway caps lease TTLs", () => + Effect.gen(function* () { + const pool = yield* fakePool({ maxTtlMs: 5 * 60_000 }); + const host = yield* makeHost(pool, config(), yield* Scope.make()); + const ready = yield* host.ensureReady(() => Effect.void); + const [iphone] = (yield* ready.devices.list).devices; + const leaseId = yield* ready.devices.boot(iphone!); + + yield* TestClock.adjust("6 minutes"); + expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe( + true, + ); + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + it.effect("returns a lease whose open finishes after the host stopped", () => Effect.gen(function* () { const holdOpen = { diff --git a/apps/server/src/device/SimlockDeviceHost.ts b/apps/server/src/device/SimlockDeviceHost.ts index bab0558614dc2..417399c9114c8 100644 --- a/apps/server/src/device/SimlockDeviceHost.ts +++ b/apps/server/src/device/SimlockDeviceHost.ts @@ -42,9 +42,9 @@ const REQUEST_TIMEOUT = Duration.seconds(15); // The gateway queues a lease request for up to five minutes when every device is busy. const OPEN_TIMEOUT = Duration.minutes(7); const COMMAND_TIMEOUT = Duration.minutes(2); -// Renewal keeps a watched but idle device; a lease this server stops renewing ends after LEASE_TTL. +// Renewal keeps a watched but idle device. It sends no ttlMs: Simlock then keeps the lease's own +// length, while one above the gateway's lease.maxTtlMs is refused rather than shortened. const RENEW_INTERVAL = Duration.minutes(2); -const LEASE_TTL_MS = 10 * 60_000; const STREAM_PATH = /^\/vendor\/serve-sim\/helper\/([^/]+)\/stream\.avcc$/; const INPUT_PATH = "/vendor/serve-sim/helper/ws"; @@ -422,7 +422,6 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* ( lease.token, "POST", `/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`, - { ttlMs: LEASE_TTL_MS }, ).pipe(Effect.result); if (renewed._tag === "Success") continue; const error = renewed.failure; diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.ts index 5bba5d084c543..8249afb1e51c1 100644 --- a/apps/server/src/device/SshDeviceHost.test.ts +++ b/apps/server/src/device/SshDeviceHost.test.ts @@ -2,7 +2,9 @@ import { expect, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Net from "@t3tools/shared/Net"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; @@ -196,6 +198,97 @@ it.effect("preserves installed status after probes and cleans failed agent activ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); +it.effect("releases the forward of a bootstrap interrupted before its hub answered", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const home = yield* fs.makeTempDirectoryScoped(); + const probing = yield* Deferred.make(); + let holdReadiness = true; + let forwards = 0; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const forwarding = command._tag === "StandardCommand" && command.args.includes("-L"); + if (forwarding) { + forwards++; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + forwards--; + }), + ); + } + const output = forwarding + ? "" + : JSON.stringify({ + nodePath: "/node", + platforms: [{ platform: "ios", available: true }], + hubPort: 1234, + helpers: { serveSimAxSettings: null, serveSimCli: null }, + }); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.make(new TextEncoder().encode(output)), + stderr: Stream.empty, + all: Stream.empty, + exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(forwarding), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ); + const publishing = yield* Deferred.make(); + let holdReadyStatus = false; + const host = yield* SshDeviceHost.make( + { + kind: "ssh", + id: "test", + label: "Test", + target: "test.example", + }, + undefined, + (status) => + status === "ready" && holdReadyStatus + ? Deferred.succeed(publishing, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.void, + ).pipe( + Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + if (holdReadiness) { + yield* Deferred.succeed(probing, undefined); + return yield* Effect.never; + } + return HttpClientResponse.fromWeb(request, new Response("ok")); + }), + ), + ), + ); + const first = yield* host.ensureReady(() => Effect.void).pipe(Effect.forkChild); + yield* Deferred.await(probing); + yield* Fiber.interrupt(first); + expect(forwards).toBe(0); + holdReadiness = false; + yield* host.ensureReady(() => Effect.void); + yield* host.stop; + expect(forwards).toBe(0); + holdReadyStatus = true; + const second = yield* host.ensureReady(() => Effect.void).pipe(Effect.forkChild); + yield* Deferred.await(publishing); + yield* Fiber.interrupt(second); + holdReadyStatus = false; + yield* host.ensureReady(() => Effect.void); + expect(forwards).toBe(1); + yield* host.stop; + expect(forwards).toBe(0); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + it.effect("lists Android devices without probing the host again once it reports Android", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index d769a85ddb080..c1d57869ead95 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -473,13 +473,21 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( return next; }); + const closeConnection = Effect.suspend(() => { + const failedScope = connectionScope; + connectionScope = null; + ready = null; + return failedScope ? Scope.close(failedScope, Exit.void) : Effect.void; + }); + const connect = Effect.fn("SshDeviceHost.connect")(function* () { for (let attempt = 0; ; attempt++) { - const result = yield* connectOnce().pipe(Effect.result); + const result = yield* connectOnce().pipe( + Effect.onInterrupt(() => closeConnection), + Effect.result, + ); if (result._tag === "Success") return result.success; - const failedScope = connectionScope; - connectionScope = null; - if (failedScope) yield* Scope.close(failedScope, Exit.void); + yield* closeConnection; // SSH binds after the reservation is released, so a competing bind needs fresh ports. if ( attempt >= 2 || diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.ts index d855320d3103c..f048b88bbfefc 100644 --- a/apps/server/src/device/sshDeviceScript.test.ts +++ b/apps/server/src/device/sshDeviceScript.test.ts @@ -46,6 +46,21 @@ it.effect("preserves shell metacharacters and newlines in remote arguments", () }), ); +it.effect("rejects a Node release below the pinned agent-device engine floor", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const probe = NodeChildProcess.spawnSync(process.execPath, [], { + input: + `Object.defineProperty(process.versions, "node", { value: "22.11.0" });\n` + + remoteDeviceScript("owner", "probe"), + env: { HOME: NodeOS.tmpdir(), PATH: NodePath.dirname(process.execPath) }, + encoding: "utf8", + }); + expect(probe.status).not.toBe(0); + expect(probe.stderr).toContain("Node 22.12 or newer"); + }), +); + it.effect("stops a daemon left for its owner when starting without agent tools", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.ts index 2e3e895293fa3..beb998e04008d 100644 --- a/apps/server/src/device/sshDeviceScript.ts +++ b/apps/server/src/device/sshDeviceScript.ts @@ -139,7 +139,8 @@ async function install(name, version, entry) { { platform: 'android', available: android, ...(!android ? { reason: 'Android SDK missing. Set ANDROID_HOME or put adb on the SSH PATH.' } : {}) }, ]; if (mode === 'probe') { - if (Number(process.versions.node.split('.')[0]) < 22) throw Error('Node 22 or newer is required on the device host.'); + const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number); + if (nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 12)) throw Error('Node 22.12 or newer is required on the device host.'); if (run('npm', ['--version']).status !== 0) throw Error('npm is missing from the non-interactive SSH PATH.'); console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions() })); return; } diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 2580aa7f67809..6548b2ccd8c0e 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -366,7 +366,7 @@ describe("DirectEndpoints Tailscale Serve", () => { yield* Deferred.succeed(finishRevalidation, undefined); expect(yield* Fiber.join(revalidating)).toEqual([bound]); expect(yield* service.resolveAvailable()).toEqual([bound]); - }).pipe(Effect.scoped), + }), ); effectIt.effect("leaves the tailnet name out when Serve is not forwarding", () => diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 06c9b0cb90551..2c79189878e8a 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -227,6 +227,7 @@ export const make = Effect.gen(function* () { fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES }, pullRequests: true, pullRequestChecks: true, + linkedThreadRefreshes: true, sideChats: true, vcsBranchStatus: true, inlineMessageContext: true, @@ -273,6 +274,7 @@ export const make = Effect.gen(function* () { projectCloneTracking: true, projectOrganization: true, ignoredFileListing: true, + ignoredFileSearch: true, triage: true, oneTimeSchedules: true, freshContext: true, diff --git a/apps/server/src/environment/staleWhileRevalidate.test.ts b/apps/server/src/environment/staleWhileRevalidate.test.ts index 6fa0faa9c4cbe..03216a4febdfe 100644 --- a/apps/server/src/environment/staleWhileRevalidate.test.ts +++ b/apps/server/src/environment/staleWhileRevalidate.test.ts @@ -21,7 +21,7 @@ it.effect("computes once, then answers from memory until the ttl lapses", () => yield* TestClock.adjust("59 seconds"); assert.equal(yield* read, 1); assert.equal(yield* Ref.get(calls), 1); - }).pipe(Effect.scoped), + }), ); it.effect("serves the stale value while one background refresh replaces it", () => @@ -80,7 +80,7 @@ it.effect("shares one first scan that an interrupted caller does not cancel", () yield* Deferred.succeed(release, undefined); assert.equal(yield* Fiber.join(next), 1); assert.equal(yield* Ref.get(calls), 1); - }).pipe(Effect.scoped), + }), ); it.effect("starts over after a failed first scan", () => @@ -98,7 +98,7 @@ it.effect("starts over after a failed first scan", () => assert.isTrue(Exit.isFailure(yield* Effect.exit(read))); assert.equal(yield* read, 2); - }).pipe(Effect.scoped), + }), ); it.effect("abandons a hung refresh so a later call can start another", () => @@ -144,7 +144,7 @@ it.effect("abandons a hung refresh so a later call can start another", () => yield* Fiber.await(yield* Deferred.await(refreshed)); assert.equal(yield* Ref.get(calls), 3); assert.equal(yield* read, 3); - }).pipe(Effect.scoped), + }), ); it.effect("interrupts a background refresh when the owning scope closes", () => diff --git a/apps/server/src/environmentTheme.test.ts b/apps/server/src/environmentTheme.test.ts index bb3b74c668e6c..e44f32e60f5ab 100644 --- a/apps/server/src/environmentTheme.test.ts +++ b/apps/server/src/environmentTheme.test.ts @@ -59,7 +59,7 @@ const withEnvironmentThemes = ( ), ), ); - }).pipe(Effect.scoped); + }); const currentThemes = Effect.gen(function* () { const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 731c19dfa1a87..a614ebdfb5687 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -53,6 +53,14 @@ export class GitWorkflowService extends Context.Service< input: VcsStatusInput, ) => Effect.Effect; readonly currentBranch: (cwd: string) => Effect.Effect; + readonly upstreamDivergence: (cwd: string) => Effect.Effect< + { + readonly refName: string; + readonly aheadCount: number; + readonly behindCount: number; + } | null, + GitManagerServiceError + >; readonly remoteStatus: ( input: VcsStatusInput, options?: GitManager.GitRemoteStatusOptions, @@ -363,6 +371,16 @@ export const make = Effect.gen(function* () { detail: "Failed to read the checked-out branch.", }); }), + upstreamDivergence: Effect.fn("GitWorkflowService.upstreamDivergence")(function* (cwd) { + const details = yield* git.statusDetailsRemote(cwd, { refreshUpstream: false }); + return details.hasUpstream && details.branch !== null + ? { + refName: details.branch, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + } + : null; + }), remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) { return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index 9d84d29e43e1a..a5a89e3d19707 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -622,6 +622,6 @@ fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => { }).pipe(Effect.provide(layerHtmlRender(executable))); expect(requests).toEqual([]); expect(datagrams).toEqual([]); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/htmlRender/publicProxy.test.ts b/apps/server/src/htmlRender/publicProxy.test.ts index f04b7fafb30b5..a268e4581b60a 100644 --- a/apps/server/src/htmlRender/publicProxy.test.ts +++ b/apps/server/src/htmlRender/publicProxy.test.ts @@ -121,7 +121,7 @@ describe("publicProxy", () => { const { code, socket } = yield* connectThrough(port, ipv4Target("1.1.1.1", 0)); socket.destroy(); expect(code).toBe(7); - }).pipe(Effect.scoped), + }), ); it.effect("refuses fake-IP names and records hosts whose every address is fake", () => @@ -133,7 +133,7 @@ describe("publicProxy", () => { expect(code).toBe(2); } expect([...fakeIpHosts]).toEqual([["cdn.fake-ip.test", "198.18.2.40"]]); - }).pipe(Effect.scoped), + }), ); it.effect("refuses every address this machine holds, even a public one", () => @@ -156,7 +156,7 @@ describe("publicProxy", () => { socket.destroy(); expect(code).toBe(2); } - }).pipe(Effect.scoped), + }), ); it.effect("closes every connection when its scope closes", () => diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 2abf86bffc46b..e7004ed5ef1b5 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -276,7 +276,6 @@ it.effect.each([ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), ), - Effect.scoped, ), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 6a90e14825cfe..ca629500f04ec 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1097,21 +1097,16 @@ const withToolAnalytics = const scheduledRunOf = (threadId: string, runId: RunId | null) => Option.isNone(threads) || runId === null ? Effect.succeed(false) - : threads.value - .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], { + : Effect.gen(function* () { + const id = ThreadId.make(threadId); + const { runs } = yield* threads.value.getThreadRecords(id, ["runs"], { runIds: [runId], - messageRoles: ["user"], - }) - .pipe( - Effect.map((records) => { - const run = records.runs.find((candidate) => candidate.id === runId); - return records.messages.some( - (message) => - message.id === run?.userMessageId && message.scheduledTaskId !== undefined, - ); - }), - Effect.orElseSucceed(() => false), - ); + }); + const run = runs.find((candidate) => candidate.id === runId); + if (run === undefined) return false; + const messages = yield* threads.value.getMessagesById(id, [run.userMessageId]); + return messages.get(run.userMessageId)?.scheduledTaskId !== undefined; + }).pipe(Effect.orElseSucceed(() => false)); const record = /* Request instrumentation already owns the span; keep this helper in that context. */ Effect.fnUntraced( diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 193c31b23bc03..ef2b6bf417856 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -2,6 +2,7 @@ import * as McpClientThreads from "../persistence/McpClientThreads.ts"; import { EnvironmentId, NodeId, + type OrchestratorMcpThreadReadResult, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, ProjectId, @@ -136,7 +137,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov number, url: `https://github.com/acme/web/pull/${number}`, source: "agent", - linkedAt: "2026-08-04T11:00:00.000Z", + linkedAt: `2026-08-04T11:0${number}:00.000Z`, snapshot: { state }, stack: null, ...(watched @@ -163,7 +164,11 @@ it("readThread preserves caller access errors and prefers activity-run status ov instanceId: parentInstanceId, model: "gpt-5.4", }), - pullRequests: [pullRequestLink(1, "merged", false), pullRequestLink(2, "open", true)], + pullRequests: [ + pullRequestLink(1, "merged", false), + pullRequestLink(2, "open", true), + ...[3, 4, 5, 6, 7, 8].map((number) => pullRequestLink(number, "open", false)), + ], }, runs: [ makeRun({ id: activeRunId, ordinal: 1, status: "running" }), @@ -250,8 +255,10 @@ it("readThread preserves caller access errors and prefers activity-run status ov { taskId: "task-subagent", kind: "subagent", childThreadId }, ]); // Every page read must not repeat each linked PR, and an open PR shows whether it is watched. + // A thread with many open PRs previews a few, watched first, then newest. const listed = result.thread.pullRequests ?? []; - expect(listed.map((link) => link.number)).not.toContain(1); + expect(listed.map((link) => link.number)).toEqual([2, 8, 7, 6, 5]); + expect(result.thread.openPullRequestCount).toBe(7); expect(listed.find((link) => link.number === 2)).toMatchObject({ watching: true, watchStartedAt: "2026-08-04T11:30:00.000Z", @@ -261,7 +268,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov afterPosition: 0, }); expect(laterPage.thread.pullRequests).toBeUndefined(); - expect(laterPage.thread.pullRequestCount).toBe(2); + expect(laterPage.thread.pullRequestCount).toBe(8); callerUnavailable = true; const denied = yield* service @@ -514,6 +521,134 @@ it("readThread returns the newest items that fit the response budget", async () }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("readThread keeps an activity page within an MCP client's output limit and pages the rest", async () => { + const projection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const rows = Array.from({ length: 60 }, (_, position) => ({ + position, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make(`turn-item-mcp-reasoning-${position}`), + item: { + type: "reasoning", + runId: activeRunId, + status: "completed", + // Command titles can carry a whole command. + title: position === 1 ? "標".repeat(60_000) : null, + text: position === 0 ? "😀a".repeat(30_000) : `${position} `.padEnd(3_000, "x"), + updatedAt: now, + }, + })); + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadEventSequence: () => Effect.succeed(1), + getTimelinePage: (_threadId, options) => { + const after = + options.itemId === undefined + ? rows.filter((row) => row.position > (options.afterPosition ?? -1)) + : rows.filter((row) => row.sourceItemId === options.itemId); + return Effect.succeed({ + items: after.slice( + 0, + options.limit, + ) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], + totalItems: rows.length, + hasMore: after.length > options.limit, + hasEarlier: false, + }); + }, + getThreadRecords: () => Effect.succeed(projection), + getProjectThreadRecords: () => Effect.succeed(projection), + getThreadShell: () => + Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [] }), + } satisfies Partial), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const positions: Array = []; + let afterPosition: number | undefined; + for (let page = 0; page < rows.length; page++) { + const result = yield* service.readThread(makeScope(), { + threadId: parentThreadId, + view: "activity", + limit: 100, + maxCharsPerItem: 1_500, + afterPosition: afterPosition ?? -1, + }); + // Claude Code rejects MCP results over 25k tokens; CJK text is about a token per char. + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000); + if (page === 0) expect(result.hasMore).toBe(true); + positions.push(...result.items.map((item) => item.position)); + if (!result.hasMore) break; + afterPosition = result.nextPosition ?? undefined; + } + expect(positions).toEqual(rows.map((row) => row.position)); + + const longText = rows[0]!.item.text; + const pages: Array = []; + let textOffset: number | null = 0; + while (textOffset !== null) { + const result: OrchestratorMcpThreadReadResult = yield* service.readThread(makeScope(), { + threadId: parentThreadId, + view: "activity", + itemId: rows[0]!.sourceItemId, + textOffset, + maxCharsPerItem: 50_000, + }); + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000); + const [item] = result.items; + expect(item?.text?.isWellFormed()).toBe(true); + pages.push(item!.text!); + textOffset = item!.nextTextOffset ?? null; + } + expect(pages.length).toBeGreaterThan(1); + expect(pages.join("")).toBe(longText); + + (projection.thread as { title: string }).title = "標".repeat(30_000); + const underHugeTitle = yield* service.readThread(makeScope(), { + threadId: parentThreadId, + view: "activity", + itemId: rows[0]!.sourceItemId, + maxCharsPerItem: 50_000, + }); + expect(underHugeTitle.items[0]?.text?.length).toBeGreaterThan(1_000); + }).pipe(Effect.provide(layer), Effect.runPromise); +}); + it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => { const parentProjection = { thread: baseThread({ diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 1fba376746dd8..e0d5febad5d34 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -2233,176 +2233,171 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); - it.live.each([ + it.effect.each([ { name: "parent instance", parentEnabled: true, model: "gpt-5.4" }, { name: "alternate instance", parentEnabled: false, model: "gpt-5.5" }, ])( "replays accepted creation on the $name without authorizing new disabled work", ({ parentEnabled, model }) => - Effect.scoped( - Effect.gen(function* () { - const altInstanceId = ProviderInstanceId.make("codex-alt"); - const driver = ProviderDriverKind.make("codex"); - const cwd = yield* checkpointWorkspace("mcp-create-retry"); - const layerRegistry = ProviderAdapterRegistry.layerFromAdapters( - [codexInstanceId, altInstanceId].map((instanceId) => ({ - instanceId, - driver, - getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), - planSelectionTransition: () => - Effect.succeed({ type: "apply_on_next_turn" as const }), - openSession: () => - Effect.die("These tests exercise committed commands before provider execution."), - })), - ); - const layerDatabase = SqlitePersistence.layerMemory; - const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( - { name: "mcp-create-retry", runtimePolicyOverride: { cwd } }, - layerRegistry, - { databaseLayer: layerDatabase, runEffectWorker: false }, - ); - const layerSettings = ServerSettings.layerTest({ - providerInstances: { - [codexInstanceId]: { driver: "codex", enabled: true }, - [altInstanceId]: { driver: "codex", enabled: true }, - }, - projectSettingsOverrides: { - [projectId]: { providerInstances: { [codexInstanceId]: { enabled: parentEnabled } } }, - }, - }); - const layerThreads = ThreadManagementService.layer.pipe( - Layer.provideMerge(layerOrchestrator), - Layer.provide( - LegacyV1ThreadImporter.layer.pipe( - Layer.provide(layerOrchestrator), - Layer.provide(layerDatabase), - ), + Effect.gen(function* () { + const altInstanceId = ProviderInstanceId.make("codex-alt"); + const driver = ProviderDriverKind.make("codex"); + const cwd = yield* checkpointWorkspace("mcp-create-retry"); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters( + [codexInstanceId, altInstanceId].map((instanceId) => ({ + instanceId, + driver, + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => + Effect.die("These tests exercise committed commands before provider execution."), + })), + ); + const layerDatabase = SqlitePersistence.layerMemory; + const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( + { name: "mcp-create-retry", runtimePolicyOverride: { cwd } }, + layerRegistry, + { databaseLayer: layerDatabase, runEffectWorker: false }, + ); + const layerSettings = ServerSettings.layerTest({ + providerInstances: { + [codexInstanceId]: { driver: "codex", enabled: true }, + [altInstanceId]: { driver: "codex", enabled: true }, + }, + projectSettingsOverrides: { + [projectId]: { providerInstances: { [codexInstanceId]: { enabled: parentEnabled } } }, + }, + }); + const layerThreads = ThreadManagementService.layer.pipe( + Layer.provideMerge(layerOrchestrator), + Layer.provide( + LegacyV1ThreadImporter.layer.pipe( + Layer.provide(layerOrchestrator), + Layer.provide(layerDatabase), ), - Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), - Layer.provideMerge(layerSettings), - ); - const layerTest = layerOrchestratorService.pipe( - Layer.provideMerge(layerThreads), - Layer.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - layerRegistry, - layerSettings, - providerRegistryLayer([ - providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }), - providerSnapshot({ instanceId: altInstanceId, driver, model: "gpt-5.5" }), - ]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ), + ), + Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), + Layer.provideMerge(layerSettings), + ); + const layerTest = layerOrchestratorService.pipe( + Layer.provideMerge(layerThreads), + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + layerRegistry, + layerSettings, + providerRegistryLayer([ + providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }), + providerSnapshot({ instanceId: altInstanceId, driver, model: "gpt-5.5" }), + ]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const settings = yield* ServerSettings.ServerSettingsService; - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("parent:create"), - threadId: parentThreadId, - projectId, - title: "MCP parent", - modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("parent:start"), - threadId: parentThreadId, - messageId: MessageId.make("parent:message"), - text: "Create a thread.", - attachments: [], - dispatchMode: { type: "start_immediately" }, - }); - const request = { - threads: [{ target: { driverKind: driver, model } }], - clientRequestId: "create-retry", - }; - const first = yield* service.createThreads(scope, request); - const child = first.threads[0]!; - const selection = parentEnabled - ? { instanceId: codexInstanceId, model: "gpt-5.4" } - : { instanceId: altInstanceId, model: "gpt-5.5" }; - assert.equal(first.threads.length, 1); - assert.equal(child.providerInstanceId, selection.instanceId); - assert.equal(child.model, selection.model); - assert.deepEqual(yield* service.createThreads(scope, request), first); + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const settings = yield* ServerSettings.ServerSettingsService; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("parent:create"), + threadId: parentThreadId, + projectId, + title: "MCP parent", + modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("parent:start"), + threadId: parentThreadId, + messageId: MessageId.make("parent:message"), + text: "Create a thread.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const request = { + threads: [{ target: { driverKind: driver, model } }], + clientRequestId: "create-retry", + }; + const first = yield* service.createThreads(scope, request); + const child = first.threads[0]!; + const selection = parentEnabled + ? { instanceId: codexInstanceId, model: "gpt-5.4" } + : { instanceId: altInstanceId, model: "gpt-5.5" }; + assert.equal(first.threads.length, 1); + assert.equal(child.providerInstanceId, selection.instanceId); + assert.equal(child.model, selection.model); + assert.deepEqual(yield* service.createThreads(scope, request), first); - // The creation receipt exists, but this prompt has not been accepted yet. - const withPrompt = { - ...request, - threads: [{ ...request.threads[0]!, prompt: "Start work." }], - }; - const started = yield* service.createThreads(scope, withPrompt); - assert.equal(started.threads[0]?.threadId, child.threadId); - const before = yield* orchestrator.getThreadProjection(child.threadId); - assert.deepEqual(before.runs[0]?.modelSelection, selection); - assert.equal(before.messages.length, 1); - const empty = yield* service.createThreads(scope, { - ...request, - clientRequestId: "empty", - }); - const emojiAtLimit = yield* service.createThreads(scope, { - threads: [{ ...request.threads[0]!, prompt: `${"a".repeat(76)}😀 and more work.` }], - clientRequestId: "emoji-title", - }); - const titled = yield* orchestrator.getThreadProjection( - emojiAtLimit.threads[0]!.threadId, - ); - assert.equal(titled.thread.title, `${"a".repeat(76)}...`); + // The creation receipt exists, but this prompt has not been accepted yet. + const withPrompt = { + ...request, + threads: [{ ...request.threads[0]!, prompt: "Start work." }], + }; + const started = yield* service.createThreads(scope, withPrompt); + assert.equal(started.threads[0]?.threadId, child.threadId); + const before = yield* orchestrator.getThreadProjection(child.threadId); + assert.deepEqual(before.runs[0]?.modelSelection, selection); + assert.equal(before.messages.length, 1); + const empty = yield* service.createThreads(scope, { + ...request, + clientRequestId: "empty", + }); + const emojiAtLimit = yield* service.createThreads(scope, { + threads: [{ ...request.threads[0]!, prompt: `${"a".repeat(76)}😀 and more work.` }], + clientRequestId: "emoji-title", + }); + const titled = yield* orchestrator.getThreadProjection(emojiAtLimit.threads[0]!.threadId); + assert.equal(titled.thread.title, `${"a".repeat(76)}...`); - yield* settings.updateSettings({ - projectSettingsOverrides: { - [projectId]: { - providerInstances: { - [codexInstanceId]: { enabled: false }, - [altInstanceId]: { enabled: false }, - }, + yield* settings.updateSettings({ + projectSettingsOverrides: { + [projectId]: { + providerInstances: { + [codexInstanceId]: { enabled: false }, + [altInstanceId]: { enabled: false }, }, }, - }); - assert.deepEqual(yield* service.createThreads(scope, withPrompt), started); - const after = yield* orchestrator.getThreadProjection(child.threadId); - assert.deepEqual(after.thread.modelSelection, selection); - assert.deepEqual(after.runs, before.runs); - assert.deepEqual(after.messages, before.messages); + }, + }); + assert.deepEqual(yield* service.createThreads(scope, withPrompt), started); + const after = yield* orchestrator.getThreadProjection(child.threadId); + assert.deepEqual(after.thread.modelSelection, selection); + assert.deepEqual(after.runs, before.runs); + assert.deepEqual(after.messages, before.messages); - const freshError = yield* service - .createThreads(scope, { - ...request, - clientRequestId: "fresh", - }) - .pipe(Effect.flip); - assert.equal(freshError.code, "provider_unavailable"); - const promptError = yield* service - .createThreads(scope, { - ...withPrompt, - clientRequestId: "empty", - }) - .pipe(Effect.flip); - assert.equal(promptError.code, "invalid_request"); - assert.include(promptError.message, "disabled"); - const untouched = yield* orchestrator.getThreadProjection(empty.threads[0]!.threadId); - assert.equal(untouched.messages.length, 0); - assert.equal(untouched.runs.length, 0); - }).pipe(Effect.provide(layerTest)); - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ), + const freshError = yield* service + .createThreads(scope, { + ...request, + clientRequestId: "fresh", + }) + .pipe(Effect.flip); + assert.equal(freshError.code, "provider_unavailable"); + const promptError = yield* service + .createThreads(scope, { + ...withPrompt, + clientRequestId: "empty", + }) + .pipe(Effect.flip); + assert.equal(promptError.code, "invalid_request"); + assert.include(promptError.message, "disabled"); + const untouched = yield* orchestrator.getThreadProjection(empty.threads[0]!.threadId); + assert.equal(untouched.messages.length, 0); + assert.equal(untouched.runs.length, 0); + }).pipe(Effect.provide(layerTest)); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it.effect.each(["local", "remote"] as const)( @@ -4878,140 +4873,137 @@ describe("OrchestratorMcpService thread stop", () => { stop: { reason: "Make room", message: "Stopped by an agent: Make room" }, }, ])("t3_thread_interrupt stop reports the run it interrupted on $name", ({ queued, stop }) => - Effect.scoped( - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("mcp-thread-stop"); - const layerAdapters = ProviderAdapterRegistry.layerSingle(liveAdapter(cwd)); - const layerDatabase = SqlitePersistence.layerMemory; - const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( - { name: "mcp-thread-stop" }, - layerAdapters, - { databaseLayer: layerDatabase, runEffectWorker: false }, - ); - const layerThreads = ThreadManagementService.layer.pipe( - Layer.provideMerge(layerOrchestrator), - Layer.provide(ServerSettings.layerTest()), - Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), - ); - const layerTest = layerOrchestratorService.pipe( - Layer.provideMerge(layerThreads), - Layer.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - layerAdapters, - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ), + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("mcp-thread-stop"); + const layerAdapters = ProviderAdapterRegistry.layerSingle(liveAdapter(cwd)); + const layerDatabase = SqlitePersistence.layerMemory; + const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( + { name: "mcp-thread-stop" }, + layerAdapters, + { databaseLayer: layerDatabase, runEffectWorker: false }, + ); + const layerThreads = ThreadManagementService.layer.pipe( + Layer.provideMerge(layerOrchestrator), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), + ); + const layerTest = layerOrchestratorService.pipe( + Layer.provideMerge(layerThreads), + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + layerAdapters, + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const send = (text: string, type: "start_immediately" | "queue_after_active") => - orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`send:${text}`), - threadId, - messageId: MessageId.make(`message:${text}`), - text, - attachments: [], - dispatchMode: { type }, - createdBy: "user", - creationSource: "web", - }); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create"), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const send = (text: string, type: "start_immediately" | "queue_after_active") => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${text}`), threadId, - projectId: ProjectId.make("project:mcp-stop"), - title: "Stop", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, + messageId: MessageId.make(`message:${text}`), + text, + attachments: [], + dispatchMode: { type }, createdBy: "user", creationSource: "web", }); - const running = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "provider-turn.updated" && event.payload.status === "running", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* send("work", "start_immediately"); - yield* worker.drain(); - yield* Fiber.join(running); - if (queued) yield* send("later", "queue_after_active"); - const before = yield* orchestrator.getThreadProjection(threadId); - const runningRun = before.runs.find((run) => run.status === "running")!; - assert.equal(before.runs.filter((run) => run.status === "queued").length, queued ? 1 : 0); - // A task the thread delegated, running when the thread is stopped. - const childRunning = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "provider-turn.updated" && - event.threadId !== threadId && - event.payload.status === "running", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* orchestrator.dispatch({ - type: "delegated_task.request", - commandId: CommandId.make("delegate"), - parentThreadId: threadId, - parentRunId: runningRun.id, - parentNodeId: runningRun.rootNodeId!, - task: "child work", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - createdBy: "agent", - creationSource: "mcp", - }); - yield* worker.drain(); - yield* Fiber.join(childRunning); - const childThreadId = (yield* orchestrator.getThreadProjection(threadId)).subagents[0]! - .childThreadId!; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:mcp-stop"), + title: "Stop", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* send("work", "start_immediately"); + yield* worker.drain(); + yield* Fiber.join(running); + if (queued) yield* send("later", "queue_after_active"); + const before = yield* orchestrator.getThreadProjection(threadId); + const runningRun = before.runs.find((run) => run.status === "running")!; + assert.equal(before.runs.filter((run) => run.status === "queued").length, queued ? 1 : 0); + // A task the thread delegated, running when the thread is stopped. + const childRunning = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "provider-turn.updated" && + event.threadId !== threadId && + event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId: threadId, + parentRunId: runningRun.id, + parentNodeId: runningRun.rootNodeId!, + task: "child work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + yield* worker.drain(); + yield* Fiber.join(childRunning); + const childThreadId = (yield* orchestrator.getThreadProjection(threadId)).subagents[0]! + .childThreadId!; - const stopped = yield* service.interruptThread(client, { - threadId, - stop: true, - clientRequestId: "stop", - ...(stop.reason === undefined ? {} : { reason: stop.reason }), - }); - assert.deepEqual(stopped, { - threadId, - runId: runningRun.id, - status: "interrupt_requested", - }); - // An agent's Stop must not read as the user's, on its thread or a task it delegated. - const interruptMessages = (id: ThreadId) => - orchestrator - .getThreadProjection(id) - .pipe( - Effect.map(({ turnItems }) => - turnItems.flatMap((item) => - item.type === "run_interrupt_request" ? [item.message] : [], - ), + const stopped = yield* service.interruptThread(client, { + threadId, + stop: true, + clientRequestId: "stop", + ...(stop.reason === undefined ? {} : { reason: stop.reason }), + }); + assert.deepEqual(stopped, { + threadId, + runId: runningRun.id, + status: "interrupt_requested", + }); + // An agent's Stop must not read as the user's, on its thread or a task it delegated. + const interruptMessages = (id: ThreadId) => + orchestrator + .getThreadProjection(id) + .pipe( + Effect.map(({ turnItems }) => + turnItems.flatMap((item) => + item.type === "run_interrupt_request" ? [item.message] : [], ), - ); - assert.deepEqual(yield* interruptMessages(threadId), [stop.message]); - assert.deepEqual(yield* interruptMessages(childThreadId), [stop.message]); - }).pipe(Effect.provide(layerTest)); - }), - ), + ), + ); + assert.deepEqual(yield* interruptMessages(threadId), [stop.message]); + assert.deepEqual(yield* interruptMessages(childThreadId), [stop.message]); + }).pipe(Effect.provide(layerTest)); + }), ); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 38b7f02342898..6dd268956a01b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -83,6 +83,7 @@ import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3too import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import { threadPullRequestUpdatedAtMs } from "@t3tools/shared/threadPullRequests"; import { normalizeThreadPullRequestKey, visibleThreadPullRequests, @@ -113,7 +114,12 @@ import type { ProjectionRecordField, ProjectionRecordFilter, } from "../orchestration-v2/ProjectionStore.ts"; -import { delegatedTaskResultRun, runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts"; +import { + delegatedTaskAwaitsSubagents, + delegatedTaskResultRun, + delegatedTaskRuns, + runOutcome, +} from "../orchestration-v2/RestartBackgroundNote.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import { mayHaveRestartContinuation, runStopDetail } from "../orchestration-v2/RunStop.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; @@ -163,10 +169,10 @@ const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; const DEFAULT_THREAD_ITEM_MAX_CHARS = 500; -// Claude Code saves MCP results over ~25k tokens to a file instead of showing them. Thread JSON -// runs about 2 chars per token, so a read stops adding items here and reports the rest as more. -const THREAD_READ_BUDGET_CHARS = 30_000; -const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const THREAD_PULL_REQUEST_PREVIEW_LIMIT = 5; +// Claude Code saves MCP results over ~25k tokens to a file instead of showing them. Bytes, not +// chars: CJK text runs near one token per char, which a char budget lets through at 30k tokens. +const THREAD_READ_RESULT_MAX_BYTES = 30_000; interface ResolvedTarget { readonly modelSelection: ModelSelection; @@ -270,6 +276,7 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure { return failure("run_not_found", error.message); case "ThreadManagementThreadArchivedError": case "ThreadManagementNoSteerableRunError": + case "ThreadManagementWorktreeRestoreError": return failure("thread_not_sendable", error.message); case "ThreadManagementThreadNotInterruptibleError": return failure("thread_not_interruptible", error.message); @@ -643,14 +650,12 @@ function taskResultTransfer( function pageIncludesTerminalTaskResult(input: { readonly parentThreadId: ThreadId; - readonly page: ReadonlyArray; + readonly items: ReadonlyArray; readonly task: OrchestrationV2Subagent; readonly target: Pick< OrchestrationV2ThreadProjection, "thread" | "runs" | "contextTransfers" | "messages" | "turnItems" | "providerTurns" >; - readonly maxChars: number; - readonly textOffset: number; }): boolean { const transfer = taskResultTransfer(input.parentThreadId, input.target, input.task); if (transfer === undefined) return false; @@ -663,21 +668,14 @@ function pageIncludesTerminalTaskResult(input: { const result = subagentResultForRun(input.target, run); if (result.messageId === null && result.turnItemId === null) return false; - return input.page.some((row) => { - if (row.sourceThreadId !== input.target.thread.id) return false; + return input.items.some((item) => { + if (item.sourceThreadId !== input.target.thread.id) return false; const matchesResult = - (result.turnItemId !== null && row.sourceItemId === result.turnItemId) || + (result.turnItemId !== null && item.itemId === result.turnItemId) || (result.messageId !== null && - row.item.type === "assistant_message" && - row.item.messageId === result.messageId); - if (!matchesResult) return false; - - const text = turnItemText(row.item); - return ( - text !== null && - (input.textOffset === 0 || input.textOffset < text.length) && - text.length <= textPageEnd(text, input.textOffset, input.maxChars) - ); + item.type === "assistant_message" && + item.messageId === result.messageId); + return matchesResult && item.text !== null && !item.textTruncated; }); } @@ -841,12 +839,23 @@ function threadBackgroundWork( function threadPullRequests( links: OrchestrationV2ThreadShell["pullRequests"], includeLinks = true, -): Pick { +): Pick< + OrchestratorMcpThreadListItem, + "pullRequests" | "pullRequestCount" | "openPullRequestCount" +> { const visible = visibleThreadPullRequests(links ?? []); if (!includeLinks) return { pullRequestCount: visible.length }; + const open = visible.filter( + (link) => link.snapshot?.state !== "merged" && link.snapshot?.state !== "closed", + ); return { - pullRequests: visible - .filter((link) => link.snapshot?.state !== "merged" && link.snapshot?.state !== "closed") + pullRequests: open + .toSorted( + (left, right) => + Number(right.watch !== undefined) - Number(left.watch !== undefined) || + threadPullRequestUpdatedAtMs(right) - threadPullRequestUpdatedAtMs(left), + ) + .slice(0, THREAD_PULL_REQUEST_PREVIEW_LIMIT) .map((link) => ({ host: normalizeThreadPullRequestKey(link).host, repository: link.repository, @@ -858,6 +867,7 @@ function threadPullRequests( watchStartedAt: link.watch?.startedAt ?? null, })), pullRequestCount: visible.length, + openPullRequestCount: open.length, }; } @@ -1121,6 +1131,78 @@ function timelineItem(input: { const encodeRolloverContext = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); +const jsonBytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value), "utf8"); + +/** The longest prefix length in [low, high] that `fits`, or `low - 1`. */ +function longestFitting(low: number, high: number, fits: (length: number) => boolean): number { + let best = low - 1; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + if (fits(mid)) { + best = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return best; +} + +/** The item with its text cut, and an oversized title too, until its JSON fits `maxBytes`. */ +function timelineItemWithin( + input: Parameters[0], + maxBytes: number, +): OrchestratorMcpThreadTimelineItem { + const longestText = (title: string | null) => { + const withText = (maxChars: number) => ({ ...timelineItem({ ...input, maxChars }), title }); + const chars = longestFitting(2, input.maxChars - 1, (n) => jsonBytes(withText(n)) <= maxBytes); + return withText(Math.max(chars, 1)); + }; + const item = longestText(input.row.item.title); + const title = item.title; + if (title === null || jsonBytes(item) <= maxBytes) return item; + // Half the budget for the title keeps `textOffset` pages of the text useful. + const cutTitle = (chars: number) => + title.slice(0, chars === 0 ? 0 : textPageEnd(title, 0, chars)); + const titleChars = longestFitting( + 1, + title.length - 1, + (n) => jsonBytes({ ...item, title: cutTitle(n) }) <= maxBytes / 2, + ); + return longestText(cutTitle(Math.max(titleChars, 0))); +} + +/** + * The items, read from the end the caller pages toward, whose result fits + * THREAD_READ_RESULT_MAX_BYTES; `start` is the first kept index. Never empty for a non-empty page. + */ +function timelineItemsWithinBudget( + envelope: Omit, + inputs: ReadonlyArray[0]>, + newestFirst: boolean, +): { readonly items: Array; readonly start: number } { + // An oversized envelope (say, a huge thread title) must not starve items to one char per read. + const budget = Math.max( + THREAD_READ_RESULT_MAX_BYTES - jsonBytes({ ...envelope, items: [] }), + THREAD_READ_RESULT_MAX_BYTES / 2, + ); + const items: Array = []; + let bytes = 0; + for (const input of newestFirst ? inputs.toReversed() : inputs) { + const item = timelineItem(input); + bytes += jsonBytes(item) + (items.length === 0 ? 0 : 1); + if (bytes <= budget) { + items.push(item); + continue; + } + if (items.length === 0) items.push(timelineItemWithin(input, budget)); + break; + } + return newestFirst + ? { items: items.toReversed(), start: inputs.length - items.length } + : { items, start: 0 }; +} + const make = Effect.gen(function* () { const clientThreads = yield* McpClientThreads.McpClientThreads; const random = yield* SecureRandom.SecureRandom; @@ -1600,16 +1682,18 @@ const make = Effect.gen(function* () { const childRun = delegatedTaskRun(childControls, task); const terminalRun = latestTerminalResultRun(childControls, childRun); const progress = delegatedTaskProgress(childControls); + const followupRuns = + childRun?.delegatedTaskId === task.id ? delegatedTaskRuns(childControls, task.id) : undefined; const taskResultRun = - childRun?.delegatedTaskId === task.id - ? delegatedTaskResultRun(childControls.runs, task.id) - : progress.resultRun; + followupRuns === undefined ? progress.resultRun : delegatedTaskResultRun(followupRuns); const taskWorkState = - childRun?.delegatedTaskId === task.id - ? isTerminalTaskStatus(taskStatusForRun(taskResultRun)) - ? "result_available" - : "working" - : progress.state; + followupRuns === undefined + ? progress.state + : !isTerminalTaskStatus(taskStatusForRun(taskResultRun)) + ? "working" + : delegatedTaskAwaitsSubagents(followupRuns, childControls.subagents) + ? "waiting_for_children" + : "result_available"; const resultRunIds = [ ...new Set( [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined), @@ -3356,25 +3440,17 @@ const make = Effect.gen(function* () { .toSorted((left, right) => right.ordinal - left.ordinal) .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT) .map((run) => threadRun(target, run)); - const allItems = timeline.items.map((row) => - timelineItem({ + const { items, start } = timelineItemsWithinBudget( + { thread, recentRuns, nextPosition: null, hasMore: false, earlierPosition: null }, + timeline.items.map((row) => ({ row, maxChars, messagesByThreadId, ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }), - }), + })), + newestFirst, ); - // Keep the end of the page the caller is reading toward, and at least one item. - let size = encodeJsonText({ thread, recentRuns }).length; - let kept = 0; - for (const item of newestFirst ? allItems.toReversed() : allItems) { - size += encodeJsonText(item).length + 1; - if (kept > 0 && size > THREAD_READ_BUDGET_CHARS) break; - kept++; - } - const start = newestFirst ? allItems.length - kept : 0; - const items = allItems.slice(start, start + kept); - const page = timeline.items.slice(start, start + kept); + const page = timeline.items.slice(start, start + items.length); const returnedRunIds = new Set( page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId), ); @@ -3392,7 +3468,9 @@ const make = Effect.gen(function* () { target, returnedRunIds, ); - if (parent !== undefined && scope.thread !== undefined && tasks.length > 0) { + // A read past the end of an item's text shows the agent nothing to acknowledge. + const readPastEnd = (input.textOffset ?? 0) > 0 && items.every((item) => !item.text); + if (parent !== undefined && scope.thread !== undefined && tasks.length > 0 && !readPastEnd) { for (const task of tasks) { const transfer = taskResultTransfer(parent.thread.id, target, task); const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id; @@ -3408,11 +3486,9 @@ const make = Effect.gen(function* () { if ( pageIncludesTerminalTaskResult({ parentThreadId: parent.thread.id, - page, + items, task, target: { ...target, ...resultRecords }, - maxChars, - textOffset: input.itemId === undefined ? 0 : (input.textOffset ?? 0), }) ) { yield* readTask( @@ -3431,7 +3507,7 @@ const make = Effect.gen(function* () { recentRuns, items, nextPosition: items.at(-1)?.position ?? null, - hasMore: timeline.hasMore || (!newestFirst && kept < allItems.length), + hasMore: timeline.hasMore || (!newestFirst && items.length < timeline.items.length), earlierPosition: timeline.hasEarlier || start > 0 ? (items[0]?.position ?? null) : null, } satisfies OrchestratorMcpThreadReadResult; }), diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 618b092f0d370..e6f5c432d4547 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -88,6 +88,7 @@ const cancellationPrompt = "Remain active until the parent cancels this delegate const queuedFollowupPrompt = "Complete the queued follow-up and return the final result."; const queuedFollowupResult = "Queued delegated follow-up completed."; const decodeThreadRead = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult); +const longFollowupResult = "Long delegated follow-up line. ".repeat(1_500); const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult); const decodeThreadInterruptResult = Schema.decodeUnknownEffect( @@ -209,703 +210,689 @@ describe("orchestrator MCP toolkit", () => { { label: "distinct", result: queuedFollowupResult, latestSummary: queuedFollowupResult }, { label: "identical", result: delegatedResult, latestSummary: null }, { label: "emoji", result: "😀", latestSummary: "😀" }, - { - label: "paginated", - result: "git safety ".repeat(120), - latestSummary: "git safety ".repeat(120), - }, + { label: "long", result: longFollowupResult, latestSummary: longFollowupResult }, ])("reports $label child results", ({ result, latestSummary }) => - Effect.scoped( - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("delegated-task-status"); - const rawTranscript = yield* readDelegatedTaskStatusTranscript(result); - const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( - materializeReplayTranscriptWorkspace(rawTranscript, cwd), - ); - const layerOrchestrator = ProviderReplayHarness.layerProviderReplay( - { - name: "delegated-task-status/codex", - transcript, - commands: [], - runtimePolicyOverride: { cwd }, - }, - CodexOrchestratorReplayHarness, - ); - // SQL spans carry no bound parameters, so this records which thread each tool read. - const threadRecordReads: Array<{ - readonly threadId: ThreadId; - readonly fields: ReadonlyArray; - }> = []; - const layerOrchestration = Layer.merge( - layerOrchestrator, - Layer.effect( - ThreadManagementService.ThreadManagementService, - Effect.gen(function* () { - const service = yield* ThreadManagementService.ThreadManagementService; - return ThreadManagementService.ThreadManagementService.of({ - ...service, - getThreadRecords: (threadId, fields, filter) => - Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe( - Effect.andThen(service.getThreadRecords(threadId, fields, filter)), - ), - }); - }), - ).pipe( - Layer.provide( - ThreadManagementService.layer.pipe( - Layer.provide(layerOrchestrator), - Layer.provide(ServerSettings.layerTest()), - Layer.provide( - CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("delegated-task-status"); + const rawTranscript = yield* readDelegatedTaskStatusTranscript(result); + const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( + materializeReplayTranscriptWorkspace(rawTranscript, cwd), + ); + const layerOrchestrator = ProviderReplayHarness.layerProviderReplay( + { + name: "delegated-task-status/codex", + transcript, + commands: [], + runtimePolicyOverride: { cwd }, + }, + CodexOrchestratorReplayHarness, + ); + // SQL spans carry no bound parameters, so this records which thread each tool read. + const threadRecordReads: Array<{ + readonly threadId: ThreadId; + readonly fields: ReadonlyArray; + }> = []; + const layerOrchestration = Layer.merge( + layerOrchestrator, + Layer.effect( + ThreadManagementService.ThreadManagementService, + Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + return ThreadManagementService.ThreadManagementService.of({ + ...service, + getThreadRecords: (threadId, fields, filter) => + Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe( + Effect.andThen(service.getThreadRecords(threadId, fields, filter)), ), - ), - ), - ), - ); - const layerProviderRegistry = ProviderRegistryMock.layer([ - makeProviderSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: codexModel, + }); }), - ]); - const layerTest = layerOrchestratorToolkit.pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provideMerge(SqlitePersistence.layerMemory), - Layer.provideMerge(layerOrchestration), + ).pipe( Layer.provide( - CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe( - Layer.provide(McpProviderSessions.layer), + ThreadManagementService.layer.pipe( + Layer.provide(layerOrchestrator), + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), ), ), - Layer.provide(layerProviderRegistry), - Layer.provide(ServerSettings.layerTest()), - Layer.provide(layerUnusedScheduledTaskStub), - Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), - Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), - Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), - Layer.provide(Layer.mock(ProjectService.ProjectService)({})), - Layer.provideMerge( - SecretRequests.layer.pipe( - Layer.provide(layerMemorySecretStore), - Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})), - Layer.provide(layerOrchestration), - ), + ), + ); + const layerProviderRegistry = ProviderRegistryMock.layer([ + makeProviderSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: codexModel, + }), + ]); + const layerTest = layerOrchestratorToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(SqlitePersistence.layerMemory), + Layer.provideMerge(layerOrchestration), + Layer.provide( + CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe( + Layer.provide(McpProviderSessions.layer), ), - Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), - Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ); + ), + Layer.provide(layerProviderRegistry), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerUnusedScheduledTaskStub), + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + Layer.provide(Layer.mock(ProjectService.ProjectService)({})), + Layer.provideMerge( + SecretRequests.layer.pipe( + Layer.provide(layerMemorySecretStore), + Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})), + Layer.provide(layerOrchestration), + ), + ), + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const server = yield* McpServer.McpServer; - const parentCreate = yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-replay-parent:create"), + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const server = yield* McpServer.McpServer; + const parentCreate = yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:mcp-replay-parent:create"), + threadId: parentThreadId, + projectId, + title: "MCP replay parent", + modelSelection: codexSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:mcp-replay-parent:start"), + threadId: parentThreadId, + messageId: MessageId.make("message:mcp-replay-parent:start"), + text: parentPrompt, + attachments: [], + modelSelection: codexSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator + .streamStoredEventsFrom({ threadId: parentThreadId, - projectId, - title: "MCP replay parent", - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-replay-parent:start"), + afterSequence: parentCreate.sequence, + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "provider-turn.updated" && + stored.event.payload.status === "running", + ), + Stream.runHead, + Effect.flatMap( + Option.match({ + onNone: () => Effect.die("Parent provider turn did not start."), + onSome: () => Effect.void, + }), + ), + ); + + const invocation: McpInvocationContext.McpInvocationScope = { + environmentId: EnvironmentId.make("environment:mcp-replay"), + requestNamespace: "mcp-provider-session-replay-parent", + thread: { threadId: parentThreadId, - messageId: MessageId.make("message:mcp-replay-parent:start"), - text: parentPrompt, - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "start_immediately" }, - }); - yield* orchestrator - .streamStoredEventsFrom({ - threadId: parentThreadId, - afterSequence: parentCreate.sequence, - }) + providerSessionId: "mcp-provider-session-replay-parent", + providerInstanceId: codexInstanceId, + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const invoke = (name: string, args: Record, scope = invocation) => + server + .callTool({ name, arguments: args }) .pipe( - Stream.filter( - (stored) => - stored.event.type === "provider-turn.updated" && - stored.event.payload.status === "running", - ), - Stream.runHead, - Effect.flatMap( - Option.match({ - onNone: () => Effect.die("Parent provider turn did not start."), - onSome: () => Effect.void, - }), - ), + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), ); - const invocation: McpInvocationContext.McpInvocationScope = { - environmentId: EnvironmentId.make("environment:mcp-replay"), - requestNamespace: "mcp-provider-session-replay-parent", - thread: { - threadId: parentThreadId, - providerSessionId: "mcp-provider-session-replay-parent", - providerInstanceId: codexInstanceId, - }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 1, - }; - const invoke = (name: string, args: Record, scope = invocation) => - server - .callTool({ name, arguments: args }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, scope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - - const delegationStartSequence = - yield* orchestrator.getThreadEventSequence(parentThreadId); - const delegatedCall = yield* invoke("delegate_task", { - task: delegatedPrompt, - target: { - providerInstanceId: codexInstanceId, - model: codexModel, - }, - mode: "async", - clientRequestId: "delegate-codex-replay-1", - }); - const delegatedStart = yield* decodeDelegateTaskResult( - delegatedCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegatedStart.childRunId).not.toBeNull(); - yield* orchestrator - .streamStoredEventsFrom({ - threadId: parentThreadId, - afterSequence: delegationStartSequence, - }) - .pipe( - Stream.filter( - (stored) => - stored.event.type === "context-transfer.created" && - stored.event.payload.type === "subagent_result" && - stored.event.payload.sourceThreadId === delegatedStart.childThreadId && - stored.event.payload.sourcePoint.runId === delegatedStart.childRunId, - ), - Stream.runHead, - Effect.flatMap( - Option.match({ - onNone: () => Effect.die("Delegated result transfer was not created."), - onSome: () => Effect.void, - }), - ), - ); - const delegatedStatusCall = yield* invoke("task_status", { - taskId: delegatedStart.taskId, - }); - const delegated = yield* decodeDelegateTaskResult( - delegatedStatusCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegated).toMatchObject({ - status: "completed", - summary: delegatedResult, + const delegationStartSequence = yield* orchestrator.getThreadEventSequence(parentThreadId); + const delegatedCall = yield* invoke("delegate_task", { + task: delegatedPrompt, + target: { providerInstanceId: codexInstanceId, - hasPendingChildRuns: false, - latestTerminalRunId: delegated.childRunId, - latestTerminalStatus: "completed", - latestTerminalSummary: null, - latestTerminalResultContextTransferId: null, - }); - expect(delegated.resultContextTransferId).not.toBeNull(); - - const delegatedChild = yield* orchestrator.getThreadProjection( - localChild(delegated.childThreadId), - ); - expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent"); - expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false); - const followupStartSequence = yield* orchestrator.getThreadEventSequence( - localChild(delegated.childThreadId), + model: codexModel, + }, + mode: "async", + clientRequestId: "delegate-codex-replay-1", + }); + const delegatedStart = yield* decodeDelegateTaskResult( + delegatedCall.structuredContent, + ).pipe(Effect.orDie); + expect(delegatedStart.childRunId).not.toBeNull(); + yield* orchestrator + .streamStoredEventsFrom({ + threadId: parentThreadId, + afterSequence: delegationStartSequence, + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "context-transfer.created" && + stored.event.payload.type === "subagent_result" && + stored.event.payload.sourceThreadId === delegatedStart.childThreadId && + stored.event.payload.sourcePoint.runId === delegatedStart.childRunId, + ), + Stream.runHead, + Effect.flatMap( + Option.match({ + onNone: () => Effect.die("Delegated result transfer was not created."), + onSome: () => Effect.void, + }), + ), ); - const runningFollowupCall = yield* invoke("t3_thread_send", { - threadId: localChild(delegated.childThreadId), - message: cancellationPrompt, - clientRequestId: "delegated-child-replay-running-1", - }); - const runningFollowup = yield* decodeThreadSendResult( - runningFollowupCall.structuredContent, - ).pipe(Effect.orDie); - yield* orchestrator - .streamStoredEventsFrom({ - threadId: localChild(delegated.childThreadId), - afterSequence: followupStartSequence, - }) - .pipe( - Stream.filter( - (stored) => - stored.event.type === "provider-turn.updated" && - stored.event.payload.status === "running", - ), - Stream.runHead, - Effect.flatMap( - Option.match({ - onNone: () => Effect.die("Follow-up provider turn did not start."), - onSome: () => Effect.void, - }), - ), - ); + const delegatedStatusCall = yield* invoke("task_status", { + taskId: delegatedStart.taskId, + }); + const delegated = yield* decodeDelegateTaskResult( + delegatedStatusCall.structuredContent, + ).pipe(Effect.orDie); + expect(delegated).toMatchObject({ + status: "completed", + summary: delegatedResult, + providerInstanceId: codexInstanceId, + hasPendingChildRuns: false, + latestTerminalRunId: delegated.childRunId, + latestTerminalStatus: "completed", + latestTerminalSummary: null, + latestTerminalResultContextTransferId: null, + }); + expect(delegated.resultContextTransferId).not.toBeNull(); - const queuedFollowupCall = yield* invoke("t3_thread_send", { + const delegatedChild = yield* orchestrator.getThreadProjection( + localChild(delegated.childThreadId), + ); + expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent"); + expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false); + const followupStartSequence = yield* orchestrator.getThreadEventSequence( + localChild(delegated.childThreadId), + ); + const runningFollowupCall = yield* invoke("t3_thread_send", { + threadId: localChild(delegated.childThreadId), + message: cancellationPrompt, + clientRequestId: "delegated-child-replay-running-1", + }); + const runningFollowup = yield* decodeThreadSendResult( + runningFollowupCall.structuredContent, + ).pipe(Effect.orDie); + yield* orchestrator + .streamStoredEventsFrom({ threadId: localChild(delegated.childThreadId), - message: queuedFollowupPrompt, - mode: "queue", - clientRequestId: "delegated-child-replay-queued-1", - }); - const queuedFollowup = yield* decodeThreadSendResult( - queuedFollowupCall.structuredContent, - ).pipe(Effect.orDie); - expect(queuedFollowup).toMatchObject({ - status: "queued", - delivery: "queued", - }); - - const pendingProjection = yield* orchestrator.getThreadProjection( - localChild(delegated.childThreadId), - ); - const followupTasks = (yield* orchestrator.getThreadProjection( - parentThreadId, - )).subagents.filter( - (task) => - task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId, - ); - expect(followupTasks).toHaveLength(2); - expect(followupTasks.every((task) => task.result === null)).toBe(true); - expect(followupTasks.map((task) => task.id)).toEqual([ - runningFollowup.taskId, - queuedFollowup.taskId, - ]); - expect( - pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status, - ).toBe("completed"); - expect( - pendingProjection.runs.find((run) => run.id === runningFollowup.runId)?.status, - ).toBe("running"); - expect( - pendingProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status, - ).toBe("queued"); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).runs.some( - (run) => run.status === "running", + afterSequence: followupStartSequence, + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "provider-turn.updated" && + stored.event.payload.status === "running", + ), + Stream.runHead, + Effect.flatMap( + Option.match({ + onNone: () => Effect.die("Follow-up provider turn did not start."), + onSome: () => Effect.void, + }), ), - ).toBe(true); + ); - const pendingStatusCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const pendingStatus = yield* decodeDelegateTaskResult( - pendingStatusCall.structuredContent, - ).pipe(Effect.orDie); - expect(pendingStatus).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - summary: delegatedResult, - resultContextTransferId: delegated.resultContextTransferId, - hasPendingChildRuns: true, - latestTerminalRunId: delegated.childRunId, - latestTerminalStatus: "completed", - latestTerminalSummary: null, - latestTerminalResultContextTransferId: null, - }); + const queuedFollowupCall = yield* invoke("t3_thread_send", { + threadId: localChild(delegated.childThreadId), + message: queuedFollowupPrompt, + mode: "queue", + clientRequestId: "delegated-child-replay-queued-1", + }); + const queuedFollowup = yield* decodeThreadSendResult( + queuedFollowupCall.structuredContent, + ).pipe(Effect.orDie); + expect(queuedFollowup).toMatchObject({ + status: "queued", + delivery: "queued", + }); - const finalSequence = yield* orchestrator.getThreadEventSequence( - localChild(delegated.childThreadId), - ); - const interruptCall = yield* invoke("t3_thread_interrupt", { - threadId: localChild(delegated.childThreadId), - runId: runningFollowup.runId, - reason: "Allow the queued replay follow-up to run.", - clientRequestId: "interrupt-delegated-child-replay-1", - }); - const interrupt = yield* decodeThreadInterruptResult( - interruptCall.structuredContent, - ).pipe(Effect.orDie); - expect(interrupt).toMatchObject({ - runId: runningFollowup.runId, - status: "interrupt_requested", - }); - yield* orchestrator - .streamStoredEventsFrom({ - threadId: localChild(delegated.childThreadId), - afterSequence: finalSequence, - }) - .pipe( - Stream.filter( - (stored) => - stored.event.type === "run.updated" && - stored.event.payload.id === queuedFollowup.runId && - stored.event.payload.status === "completed", - ), - Stream.runHead, - Effect.flatMap( - Option.match({ - onNone: () => Effect.die("Queued follow-up did not complete."), - onSome: () => Effect.void, - }), - ), - ); + const pendingProjection = yield* orchestrator.getThreadProjection( + localChild(delegated.childThreadId), + ); + const followupTasks = (yield* orchestrator.getThreadProjection( + parentThreadId, + )).subagents.filter( + (task) => task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId, + ); + expect(followupTasks).toHaveLength(2); + expect(followupTasks.every((task) => task.result === null)).toBe(true); + expect(followupTasks.map((task) => task.id)).toEqual([ + runningFollowup.taskId, + queuedFollowup.taskId, + ]); + expect(pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status).toBe( + "completed", + ); + expect(pendingProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe( + "running", + ); + expect(pendingProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe( + "queued", + ); + expect( + (yield* orchestrator.getThreadProjection(parentThreadId)).runs.some( + (run) => run.status === "running", + ), + ).toBe(true); - const finalProjection = yield* orchestrator.getThreadProjection( - localChild(delegated.childThreadId), - ); - expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe( - "interrupted", - ); - expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe( - "completed", + const pendingStatusCall = yield* invoke("task_status", { + taskId: delegated.taskId, + }); + const pendingStatus = yield* decodeDelegateTaskResult( + pendingStatusCall.structuredContent, + ).pipe(Effect.orDie); + expect(pendingStatus).toMatchObject({ + childRunId: delegated.childRunId, + status: "completed", + summary: delegatedResult, + resultContextTransferId: delegated.resultContextTransferId, + hasPendingChildRuns: true, + latestTerminalRunId: delegated.childRunId, + latestTerminalStatus: "completed", + latestTerminalSummary: null, + latestTerminalResultContextTransferId: null, + }); + + const finalSequence = yield* orchestrator.getThreadEventSequence( + localChild(delegated.childThreadId), + ); + const interruptCall = yield* invoke("t3_thread_interrupt", { + threadId: localChild(delegated.childThreadId), + runId: runningFollowup.runId, + reason: "Allow the queued replay follow-up to run.", + clientRequestId: "interrupt-delegated-child-replay-1", + }); + const interrupt = yield* decodeThreadInterruptResult(interruptCall.structuredContent).pipe( + Effect.orDie, + ); + expect(interrupt).toMatchObject({ + runId: runningFollowup.runId, + status: "interrupt_requested", + }); + yield* orchestrator + .streamStoredEventsFrom({ + threadId: localChild(delegated.childThreadId), + afterSequence: finalSequence, + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.payload.id === queuedFollowup.runId && + stored.event.payload.status === "completed", + ), + Stream.runHead, + Effect.flatMap( + Option.match({ + onNone: () => Effect.die("Queued follow-up did not complete."), + onSome: () => Effect.void, + }), + ), ); - expect( - finalProjection.turnItems.find( - (item) => - item.runId === runningFollowup.runId && item.type === "run_interrupt_result", + + const finalProjection = yield* orchestrator.getThreadProjection( + localChild(delegated.childThreadId), + ); + expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe( + "interrupted", + ); + expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe( + "completed", + ); + expect( + finalProjection.turnItems.find( + (item) => item.runId === runningFollowup.runId && item.type === "run_interrupt_result", + ), + ).toMatchObject({ + message: "Stopped by an agent: Allow the queued replay follow-up to run.", + }); + yield* orchestrator + .streamStoredEventsFrom({ + threadId: parentThreadId, + afterSequence: finalSequence, + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === followupTasks[1]!.id && + stored.event.payload.status === "completed", ), - ).toMatchObject({ - message: "Stopped by an agent: Allow the queued replay follow-up to run.", - }); - yield* orchestrator - .streamStoredEventsFrom({ - threadId: parentThreadId, - afterSequence: finalSequence, - }) - .pipe( - Stream.filter( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.id === followupTasks[1]!.id && - stored.event.payload.status === "completed", - ), - Stream.runHead, - Effect.flatMap( - Option.match({ - onNone: () => Effect.die("Follow-up task did not settle."), - onSome: () => Effect.void, - }), - ), - ); - const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId); - expect( - finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status, - ).toBe("interrupted"); - expect( - finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id), - ).toMatchObject({ - status: "completed", - result, - }); - expect( - finishedParent.contextTransfers.filter( - (transfer) => - transfer.type === "subagent_result" && - transfer.sourceThreadId === delegated.childThreadId, + Stream.runHead, + Effect.flatMap( + Option.match({ + onNone: () => Effect.die("Follow-up task did not settle."), + onSome: () => Effect.void, + }), ), - ).toHaveLength(3); - expect( - finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id) - ?.completionDelivery?.state, - ).toBe("claimed"); - const finalStatusCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const finalStatus = yield* decodeDelegateTaskResult( - finalStatusCall.structuredContent, - ).pipe(Effect.orDie); - expect(finalStatus).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - summary: delegatedResult, - resultContextTransferId: delegated.resultContextTransferId, - hasPendingChildRuns: false, - latestTerminalRunId: queuedFollowup.runId, - latestTerminalStatus: "completed", - latestTerminalSummary: latestSummary, - }); - const followupTransfer = finishedParent.contextTransfers.find( + ); + const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId); + expect( + finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status, + ).toBe("interrupted"); + expect( + finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id), + ).toMatchObject({ + status: "completed", + result, + }); + expect( + finishedParent.contextTransfers.filter( (transfer) => transfer.type === "subagent_result" && - transfer.sourcePoint.runId === queuedFollowup.runId, - ); - expect(followupTransfer).toBeDefined(); - expect(finalStatus.latestTerminalResultContextTransferId).toBe(followupTransfer?.id); - expect(finalStatus.latestTerminalResultContextTransferId).not.toBe( - delegated.resultContextTransferId, - ); - const transferReads: Array = []; - const messageReads: Array = []; - const runReads: Array = []; - const projectionTableReads: Array = []; - const acknowledgementReads: Array = []; - const tracer = Tracer.make({ - span(options) { - const span = new Tracer.NativeSpan(options); - const end = span.end.bind(span); - span.end = (endTime, exit) => { - end(endTime, exit); - const query = span.attributes.get("db.query.text"); - if (typeof query !== "string") return; - let parent = Option.getOrUndefined(span.parent); - while (parent?._tag === "Span") { - if ( - parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution" - ) { - acknowledgementReads.push(query); - break; - } - parent = Option.getOrUndefined(parent.parent); - } - for (const [, table] of query.matchAll( - /FROM orchestration_v2_projection_(\w+)/gi, - )) { - projectionTableReads.push(table!); - } - if ( - /SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query) - ) { - transferReads.push(query); - } - if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) { - runReads.push(query); - } + transfer.sourceThreadId === delegated.childThreadId, + ), + ).toHaveLength(3); + expect( + finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id) + ?.completionDelivery?.state, + ).toBe("claimed"); + const finalStatusCall = yield* invoke("task_status", { + taskId: delegated.taskId, + }); + const finalStatus = yield* decodeDelegateTaskResult(finalStatusCall.structuredContent).pipe( + Effect.orDie, + ); + expect(finalStatus).toMatchObject({ + childRunId: delegated.childRunId, + status: "completed", + summary: delegatedResult, + resultContextTransferId: delegated.resultContextTransferId, + hasPendingChildRuns: false, + latestTerminalRunId: queuedFollowup.runId, + latestTerminalStatus: "completed", + latestTerminalSummary: latestSummary, + }); + const followupTransfer = finishedParent.contextTransfers.find( + (transfer) => + transfer.type === "subagent_result" && + transfer.sourcePoint.runId === queuedFollowup.runId, + ); + expect(followupTransfer).toBeDefined(); + expect(finalStatus.latestTerminalResultContextTransferId).toBe(followupTransfer?.id); + expect(finalStatus.latestTerminalResultContextTransferId).not.toBe( + delegated.resultContextTransferId, + ); + const transferReads: Array = []; + const messageReads: Array = []; + const runReads: Array = []; + const projectionTableReads: Array = []; + const acknowledgementReads: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (endTime, exit) => { + end(endTime, exit); + const query = span.attributes.get("db.query.text"); + if (typeof query !== "string") return; + let parent = Option.getOrUndefined(span.parent); + while (parent?._tag === "Span") { if ( - /SELECT\s+(?:message\.)?payload_json\s+FROM orchestration_v2_projection_messages/i.test( - query, - ) + parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution" ) { - messageReads.push(query); + acknowledgementReads.push(query); + break; } - }; - return span; - }, - }); - const wait = yield* invoke( - "t3_thread_wait", - { threadId: delegated.childThreadId, runId: queuedFollowup.runId }, - { ...invocation, thread: undefined }, - ).pipe(Effect.withTracer(tracer)); - expect(wait.isError).not.toBe(true); - const expectedWait = { + parent = Option.getOrUndefined(parent.parent); + } + for (const [, table] of query.matchAll(/FROM orchestration_v2_projection_(\w+)/gi)) { + projectionTableReads.push(table!); + } + if (/SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query)) { + transferReads.push(query); + } + if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) { + runReads.push(query); + } + if ( + /SELECT\s+(?:message\.)?payload_json\s+FROM orchestration_v2_projection_messages/i.test( + query, + ) + ) { + messageReads.push(query); + } + }; + return span; + }, + }); + const wait = yield* invoke( + "t3_thread_wait", + { threadId: delegated.childThreadId, runId: queuedFollowup.runId }, + { ...invocation, thread: undefined }, + ).pipe(Effect.withTracer(tracer)); + expect(wait.isError).not.toBe(true); + const expectedWait = { + threadId: delegated.childThreadId, + runId: queuedFollowup.runId, + status: "completed", + timedOut: false, + }; + expect(wait.structuredContent).toEqual(expectedWait); + expect(messageReads).toEqual([]); + expect(transferReads).toHaveLength(0); + const settledWait = yield* invoke( + "t3_thread_wait", + { threadId: delegated.childThreadId, runId: queuedFollowup.runId, - status: "completed", - timedOut: false, - }; - expect(wait.structuredContent).toEqual(expectedWait); - expect(messageReads).toEqual([]); - expect(transferReads).toHaveLength(0); - const settledWait = yield* invoke( - "t3_thread_wait", - { - threadId: delegated.childThreadId, - runId: queuedFollowup.runId, - untilDelegatedWorkSettled: true, - }, - { ...invocation, thread: undefined }, - ).pipe(Effect.withTracer(tracer)); - expect(settledWait.isError).not.toBe(true); - expect(settledWait.structuredContent).toMatchObject({ - ...expectedWait, - resultRun: { runId: queuedFollowup.runId, status: "completed" }, + untilDelegatedWorkSettled: true, + }, + { ...invocation, thread: undefined }, + ).pipe(Effect.withTracer(tracer)); + expect(settledWait.isError).not.toBe(true); + expect(settledWait.structuredContent).toMatchObject({ + ...expectedWait, + resultRun: { runId: queuedFollowup.runId, status: "completed" }, + }); + expect(messageReads.length).toBeGreaterThan(0); + expect( + messageReads.filter((query) => query.includes("$.notification.source.kind")), + ).toHaveLength(1); + // The orchestrator's restart-continuation guard still reads its own records. + expect( + messageReads.filter((query) => !query.includes("$.notification.source.kind")), + ).toHaveLength(1); + const parentlessRead = yield* invoke( + "t3_thread_read", + { + threadId: delegated.childThreadId, + limit: 100, + maxCharsPerItem: result === "😀" ? 1 : 50_000, + }, + { ...invocation, thread: undefined }, + ).pipe(Effect.withTracer(tracer)); + expect(parentlessRead.isError).not.toBe(true); + expect(transferReads).toHaveLength(0); + const afterParentlessRead = yield* orchestrator.getThreadProjection(parentThreadId); + expect( + afterParentlessRead.subagents.find((task) => task.id === queuedFollowup.taskId) + ?.completionDelivery?.state, + ).toBe("claimed"); + + const read = yield* invoke("t3_thread_read", { + threadId: delegated.childThreadId, + limit: 100, + ...(result === "😀" ? { maxCharsPerItem: 1 } : {}), + }).pipe(Effect.withTracer(tracer)); + expect(read.isError).not.toBe(true); + expect(transferReads.length).toBeGreaterThan(0); + const firstPage = yield* decodeThreadRead(read.structuredContent); + const finalItem = firstPage.items.find((item) => item.text === result.slice(0, 500)); + expect(finalItem).toBeDefined(); + if (result.length > 500) { + yield* invoke("t3_thread_read", { + threadId: delegated.childThreadId, + itemId: finalItem!.itemId, + textOffset: result.length, }); - expect(messageReads.length).toBeGreaterThan(0); - expect( - messageReads.filter((query) => query.includes("$.notification.source.kind")), - ).toHaveLength(1); - // The orchestrator's restart-continuation guard still reads its own records. - expect( - messageReads.filter((query) => !query.includes("$.notification.source.kind")), - ).toHaveLength(1); - const parentlessRead = yield* invoke( - "t3_thread_read", - { - threadId: delegated.childThreadId, - limit: 100, - maxCharsPerItem: result === "😀" ? 1 : 20_000, - }, - { ...invocation, thread: undefined }, - ).pipe(Effect.withTracer(tracer)); - expect(parentlessRead.isError).not.toBe(true); - expect(transferReads).toHaveLength(0); - const afterParentlessRead = yield* orchestrator.getThreadProjection(parentThreadId); + } else { + expect(read.structuredContent).toEqual(parentlessRead.structuredContent); + } + let text = finalItem!.text ?? ""; + let nextTextOffset = finalItem?.nextTextOffset ?? null; + while (nextTextOffset !== null) { + const beforeContinuation = yield* orchestrator.getThreadProjection(parentThreadId); expect( - afterParentlessRead.subagents.find((task) => task.id === queuedFollowup.taskId) + beforeContinuation.subagents.find((task) => task.id === queuedFollowup.taskId) ?.completionDelivery?.state, ).toBe("claimed"); - - const read = yield* invoke("t3_thread_read", { + const continuation = yield* invoke("t3_thread_read", { threadId: delegated.childThreadId, - limit: 100, - ...(result === "😀" ? { maxCharsPerItem: 1 } : {}), + itemId: finalItem!.itemId, + textOffset: nextTextOffset, + maxCharsPerItem: 50_000, }).pipe(Effect.withTracer(tracer)); - expect(read.isError).not.toBe(true); - expect(transferReads.length).toBeGreaterThan(0); - const firstPage = yield* decodeThreadRead(read.structuredContent); - const finalItem = firstPage.items.find((item) => item.text === result.slice(0, 500)); - expect(finalItem).toBeDefined(); - if (result.length > 500) { - yield* invoke("t3_thread_read", { - threadId: delegated.childThreadId, - itemId: finalItem!.itemId, - textOffset: result.length, - }); - } else { - expect(read.structuredContent).toEqual(parentlessRead.structuredContent); - } - let text = finalItem!.text ?? ""; - let nextTextOffset = finalItem?.nextTextOffset ?? null; - while (nextTextOffset !== null) { - const beforeContinuation = yield* orchestrator.getThreadProjection(parentThreadId); - expect( - beforeContinuation.subagents.find((task) => task.id === queuedFollowup.taskId) - ?.completionDelivery?.state, - ).toBe("claimed"); - const continuation = yield* invoke("t3_thread_read", { - threadId: delegated.childThreadId, - itemId: finalItem!.itemId, - textOffset: nextTextOffset, - }).pipe(Effect.withTracer(tracer)); - const nextPage = yield* decodeThreadRead(continuation.structuredContent); - text += nextPage.items[0]?.text ?? ""; - nextTextOffset = nextPage.items[0]?.nextTextOffset ?? null; - } - expect(text).toBe(result); - // The acknowledgement reads the task and its spawning run by id, not the parent's history. - expect(acknowledgementReads.length).toBeGreaterThan(0); - expect( - acknowledgementReads.filter( - (query) => - /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) || - (/FROM orchestration_v2_projection_runs\b/.test(query) && - !query.includes("AND run_id IN")) || - (/FROM orchestration_v2_projection_subagents\b/.test(query) && - !query.includes("AND subagent_id IN")), - ), - ).toEqual([]); - const afterRead = yield* orchestrator.getThreadProjection(parentThreadId); - expect( - afterRead.subagents.find((task) => task.id === queuedFollowup.taskId) - ?.completionDelivery?.state, - ).toBe("acknowledged"); + const nextPage = yield* decodeThreadRead(continuation.structuredContent); + text += nextPage.items[0]?.text ?? ""; + nextTextOffset = nextPage.items[0]?.nextTextOffset ?? null; + } + expect(text).toBe(result); + // The acknowledgement reads the task and its spawning run by id, not the parent's history. + expect(acknowledgementReads.length).toBeGreaterThan(0); + expect( + acknowledgementReads.filter( + (query) => + /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) || + (/FROM orchestration_v2_projection_runs\b/.test(query) && + !query.includes("AND run_id IN")) || + (/FROM orchestration_v2_projection_subagents\b/.test(query) && + !query.includes("AND subagent_id IN")), + ), + ).toEqual([]); + const afterRead = yield* orchestrator.getThreadProjection(parentThreadId); + expect( + afterRead.subagents.find((task) => task.id === queuedFollowup.taskId)?.completionDelivery + ?.state, + ).toBe("acknowledged"); - const messageReadsBeforeCapabilities = messageReads.length; - const tableReadsBeforeCapabilities = projectionTableReads.length; - const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe( - Effect.withTracer(tracer), - ); - expect(capabilities.isError).not.toBe(true); - expect(messageReads).toHaveLength(messageReadsBeforeCapabilities); - // The caller check reads only the thread row, never its history. - expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual( - new Set(["threads"]), - ); - const runReadsBeforeStatus = runReads.length; - const transferReadsBeforeStatus = transferReads.length; - const threadRecordReadsBeforeStatus = threadRecordReads.length; - const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe( - Effect.withTracer(tracer), - ); - expect(statusAgain.isError).not.toBe(true); - // A task wait reads result transfers and runs from the child; the parent's stay unread. - expect(runReads).toHaveLength(runReadsBeforeStatus + 1); - expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1); - expect( - threadRecordReads - .slice(threadRecordReadsBeforeStatus) - .filter( - ({ fields }) => fields.includes("runs") || fields.includes("contextTransfers"), - ) - .map(({ threadId }) => threadId), - ).toEqual([delegated.childThreadId]); - const outside = { - ...invocation, - thread: undefined, - client: { - sessionId: "post-reader-session", - label: "Post reader", - access: "full-access" as const, + const messageReadsBeforeCapabilities = messageReads.length; + const tableReadsBeforeCapabilities = projectionTableReads.length; + const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe( + Effect.withTracer(tracer), + ); + expect(capabilities.isError).not.toBe(true); + expect(messageReads).toHaveLength(messageReadsBeforeCapabilities); + // The caller check reads only the thread row, never its history. + expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual( + new Set(["threads"]), + ); + const runReadsBeforeStatus = runReads.length; + const transferReadsBeforeStatus = transferReads.length; + const threadRecordReadsBeforeStatus = threadRecordReads.length; + const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe( + Effect.withTracer(tracer), + ); + expect(statusAgain.isError).not.toBe(true); + // A task wait reads result transfers and runs from the child; the parent's stay unread. + expect(runReads).toHaveLength(runReadsBeforeStatus + 1); + expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1); + expect( + threadRecordReads + .slice(threadRecordReadsBeforeStatus) + .filter(({ fields }) => fields.includes("runs") || fields.includes("contextTransfers")) + .map(({ threadId }) => threadId), + ).toEqual([delegated.childThreadId]); + const outside = { + ...invocation, + thread: undefined, + client: { + sessionId: "post-reader-session", + label: "Post reader", + access: "full-access" as const, + }, + }; + const readPosts = (args: Record = {}) => + invoke( + "t3_thread_read", + { + threadId: delegated.childThreadId, + view: "activity", + limit: 100, + ...args, }, - }; - const readPosts = (args: Record = {}) => - invoke( - "t3_thread_read", - { - threadId: delegated.childThreadId, - view: "activity", - limit: 100, - ...args, - }, - outside, - ).pipe(Effect.flatMap((response) => decodeThreadRead(response.structuredContent))); - const beforePost = yield* readPosts(); - const postArgs = { - threadId: delegated.childThreadId, - message: "Posted without a run", - clientRequestId: "post-read-regression", - }; - const posted = yield* invoke("t3_thread_post", postArgs, outside); - expect(posted.isError).not.toBe(true); - yield* invoke("t3_thread_post", postArgs, outside); - const sql = yield* SqlClient.SqlClient; - const postId = (posted.structuredContent as { messageId: string }).messageId; - yield* sql`UPDATE orchestration_v2_projection_turn_items SET ordinal = 1, + outside, + ).pipe(Effect.flatMap((response) => decodeThreadRead(response.structuredContent))); + const beforePost = yield* readPosts(); + const postArgs = { + threadId: delegated.childThreadId, + message: "Posted without a run", + clientRequestId: "post-read-regression", + }; + const posted = yield* invoke("t3_thread_post", postArgs, outside); + expect(posted.isError).not.toBe(true); + yield* invoke("t3_thread_post", postArgs, outside); + const sql = yield* SqlClient.SqlClient; + const postId = (posted.structuredContent as { messageId: string }).messageId; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET ordinal = 1, payload_json = json_remove(json_set(payload_json, '$.ordinal', 1), '$.postOnly') WHERE thread_id = ${delegated.childThreadId} AND json_extract(payload_json, '$.messageId') = ${postId}`; - yield* sql`UPDATE orchestration_v2_turn_item_positions SET ordinal = 1 + yield* sql`UPDATE orchestration_v2_turn_item_positions SET ordinal = 1 WHERE thread_id = ${delegated.childThreadId} AND turn_item_id IN ( SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id = ${delegated.childThreadId} AND json_extract(payload_json, '$.messageId') = ${postId})`; - yield* sql`UPDATE orchestration_v2_projection_turn_items + yield* sql`UPDATE orchestration_v2_projection_turn_items SET updated_at = '2099-01-01T00:00:00.000Z' WHERE thread_id = ${delegated.childThreadId} AND turn_item_id NOT IN ( SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id = ${delegated.childThreadId} AND json_extract(payload_json, '$.inputIntent') = 'post')`; - const tail = yield* readPosts({ - afterPosition: beforePost.thread.itemCount - 1, - sinceRevision: beforePost.revision, - }); - expect(tail.items).toHaveLength(1); - expect(tail.items[0]).toMatchObject({ - text: postArgs.message, - createdBy: "agent", - creationSource: "mcp", - runId: null, - postOnly: true, - }); - expect(tail.thread.itemCount).toBe(beforePost.thread.itemCount + 1); - expect(tail.thread.runCount).toBe(beforePost.thread.runCount); - expect(tail.revision).not.toBe(beforePost.revision); - const second = yield* invoke( - "t3_thread_post", - { ...postArgs, message: "Another post", clientRequestId: "post-read-next" }, - outside, - ); - expect(second.isError).not.toBe(true); - const nextTail = yield* readPosts({ - afterPosition: tail.nextPosition, - sinceRevision: tail.revision, - }); - expect(nextTail.items).toHaveLength(1); - expect(nextTail.items[0]).toMatchObject({ - text: "Another post", - postOnly: true, - createdBy: "agent", - creationSource: "mcp", - }); - expect(nextTail.thread.itemCount).toBe(tail.thread.itemCount + 1); - const unchanged = yield* readPosts({ sinceRevision: nextTail.revision }); - expect(unchanged.items).toEqual([]); - expect(unchanged.thread.itemCount).toBe(nextTail.thread.itemCount); - }).pipe(Effect.provide(layerTest)); - }), - ), + const tail = yield* readPosts({ + afterPosition: beforePost.thread.itemCount - 1, + sinceRevision: beforePost.revision, + }); + expect(tail.items).toHaveLength(1); + expect(tail.items[0]).toMatchObject({ + text: postArgs.message, + createdBy: "agent", + creationSource: "mcp", + runId: null, + postOnly: true, + }); + expect(tail.thread.itemCount).toBe(beforePost.thread.itemCount + 1); + expect(tail.thread.runCount).toBe(beforePost.thread.runCount); + expect(tail.revision).not.toBe(beforePost.revision); + const second = yield* invoke( + "t3_thread_post", + { ...postArgs, message: "Another post", clientRequestId: "post-read-next" }, + outside, + ); + expect(second.isError).not.toBe(true); + const nextTail = yield* readPosts({ + afterPosition: tail.nextPosition, + sinceRevision: tail.revision, + }); + expect(nextTail.items).toHaveLength(1); + expect(nextTail.items[0]).toMatchObject({ + text: "Another post", + postOnly: true, + createdBy: "agent", + creationSource: "mcp", + }); + expect(nextTail.thread.itemCount).toBe(tail.thread.itemCount + 1); + const unchanged = yield* readPosts({ sinceRevision: nextTail.revision }); + expect(unchanged.items).toEqual([]); + expect(unchanged.thread.itemCount).toBe(nextTail.thread.itemCount); + }).pipe(Effect.provide(layerTest)); + }), ); }); diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 1c193096db273..dac5153acee6b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -18,8 +18,10 @@ import { import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { PreviewBrowserRootError } from "../preview/PreviewBrowserHost.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; @@ -66,230 +68,220 @@ const requestsFrom = ( ); it.effect("atomically registers a connected host and correlates its response", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => - broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: { available: true }, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(requests, (request) => + broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: { available: true }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - const result = yield* broker.invoke<{ available: boolean }>({ - scope, - operation: "open", - input: {}, - }); + const result = yield* broker.invoke<{ available: boolean }>({ + scope, + operation: "open", + input: {}, + }); - expect(result).toEqual({ available: true }); - }), - ), + expect(result).toEqual({ available: true }); + }), ); it.effect("targets multiple tabs explicitly while retaining a default tab", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const appTabId = PreviewTabId.make("tab-web-app"); - const simulatorTabId = PreviewTabId.make("tab-ios-simulator"); - const openedTabIds = [appTabId, simulatorTabId]; - let openIndex = 0; - const routedRequests: RoutedRequest[] = []; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => { - routedRequests.push(request); - return broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: - request.operation === "open" - ? { available: true, tabId: openedTabIds[openIndex++] } - : { url: "http://localhost:3200" }, - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } }); - yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } }); - yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId }); - yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - - expect(routedRequests).toHaveLength(5); - expect(routedRequests[0]?.tabId).toBeUndefined(); - expect(routedRequests[1]?.tabId).toBe(appTabId); - expect(routedRequests[2]?.tabId).toBe(simulatorTabId); - expect(routedRequests[2]?.tabIdExplicit).toBe(false); - expect(routedRequests[3]?.tabId).toBe(appTabId); - expect(routedRequests[3]?.tabIdExplicit).toBe(true); - expect(routedRequests[4]?.tabId).toBe(appTabId); - }), - ), + Effect.gen(function* () { + const broker = yield* makeBroker; + const appTabId = PreviewTabId.make("tab-web-app"); + const simulatorTabId = PreviewTabId.make("tab-ios-simulator"); + const openedTabIds = [appTabId, simulatorTabId]; + let openIndex = 0; + const routedRequests: RoutedRequest[] = []; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(requests, (request) => { + routedRequests.push(request); + return broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: + request.operation === "open" + ? { available: true, tabId: openedTabIds[openIndex++] } + : { url: "http://localhost:3200" }, + }); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } }); + yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } }); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId }); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routedRequests).toHaveLength(5); + expect(routedRequests[0]?.tabId).toBeUndefined(); + expect(routedRequests[1]?.tabId).toBe(appTabId); + expect(routedRequests[2]?.tabId).toBe(simulatorTabId); + expect(routedRequests[2]?.tabIdExplicit).toBe(false); + expect(routedRequests[3]?.tabId).toBe(appTabId); + expect(routedRequests[3]?.tabIdExplicit).toBe(true); + expect(routedRequests[4]?.tabId).toBe(appTabId); + }), ); it.effect.each([true, false])( "keeps an older target stable while a newer explicit tab responds (implicit: %s)", (implicit) => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const olderTabId = PreviewTabId.make("tab-older-request"); - const newerTabId = PreviewTabId.make("tab-newer-request"); - const releaseOlderResponse = yield* Deferred.make(); - const routedRequests: RoutedRequest[] = []; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => { - routedRequests.push(request); - const response = Effect.gen(function* () { - if (request.tabId === olderTabId && request.operation === "snapshot") { - yield* Deferred.await(releaseOlderResponse); - } - yield* broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: { url: "http://localhost:3200" }, - }); - if (request.tabId === newerTabId) { - yield* Deferred.succeed(releaseOlderResponse, undefined); - } - }); - return response.pipe(Effect.forkScoped, Effect.asVoid); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.invoke({ scope, operation: "status", input: {}, tabId: olderTabId }); - let capturedTabId: PreviewTabId | undefined; - const older = yield* broker - .invoke({ - scope, - operation: "snapshot", - input: {}, - ...(implicit ? {} : { tabId: olderTabId }), - onTargetTab: (tabId) => { - capturedTabId = tabId; - }, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - const newer = yield* broker - .invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId }) - .pipe(Effect.forkScoped); - yield* Fiber.join(newer); - yield* Fiber.join(older); - yield* broker.invoke({ - scope, - operation: "status", - input: {}, - tabId: olderTabId, - updateCurrentTab: false, - }); - yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - - expect(routedRequests.at(-1)?.tabId).toBe(newerTabId); - expect(capturedTabId).toBe(olderTabId); - }), - ), -); - -it.effect("does not let a no-tab response suppress an earlier tab decision", () => - Effect.scoped( Effect.gen(function* () { const broker = yield* makeBroker; - const initialTabId = PreviewTabId.make("tab-initial"); - const openedTabId = PreviewTabId.make("tab-opened-late"); - const releaseOpenResponse = yield* Deferred.make(); + const olderTabId = PreviewTabId.make("tab-older-request"); + const newerTabId = PreviewTabId.make("tab-newer-request"); + const releaseOlderResponse = yield* Deferred.make(); const routedRequests: RoutedRequest[] = []; const requests = requestsFrom(yield* broker.connect(makeHost())); yield* Stream.runForEach(requests, (request) => { routedRequests.push(request); - const marker = - typeof request.input === "object" && request.input !== null && "marker" in request.input - ? request.input.marker - : undefined; const response = Effect.gen(function* () { - if (marker === "older") { - yield* Deferred.await(releaseOpenResponse); + if (request.tabId === olderTabId && request.operation === "snapshot") { + yield* Deferred.await(releaseOlderResponse); } yield* broker.respond({ clientId: "client-1", connectionId: request.connectionId, requestId: request.requestId, ok: true, - result: - request.operation === "open" - ? { available: true, tabId: marker === "older" ? openedTabId : initialTabId } - : { url: "http://localhost:3200" }, + result: { url: "http://localhost:3200" }, }); - if (marker === "newer") { - yield* Deferred.succeed(releaseOpenResponse, undefined); + if (request.tabId === newerTabId) { + yield* Deferred.succeed(releaseOlderResponse, undefined); } }); return response.pipe(Effect.forkScoped, Effect.asVoid); }).pipe(Effect.forkScoped); yield* Effect.yieldNow; - yield* broker.invoke({ scope, operation: "open", input: {} }); + yield* broker.invoke({ scope, operation: "status", input: {}, tabId: olderTabId }); + let capturedTabId: PreviewTabId | undefined; const older = yield* broker .invoke({ scope, - operation: "open", - input: { marker: "older", reuseExistingTab: false }, + operation: "snapshot", + input: {}, + ...(implicit ? {} : { tabId: olderTabId }), + onTargetTab: (tabId) => { + capturedTabId = tabId; + }, }) .pipe(Effect.forkScoped); yield* Effect.yieldNow; const newer = yield* broker - .invoke({ scope, operation: "snapshot", input: { marker: "newer" } }) + .invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId }) .pipe(Effect.forkScoped); yield* Fiber.join(newer); yield* Fiber.join(older); + yield* broker.invoke({ + scope, + operation: "status", + input: {}, + tabId: olderTabId, + updateCurrentTab: false, + }); yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - expect(routedRequests.at(-1)?.tabId).toBe(openedTabId); + expect(routedRequests.at(-1)?.tabId).toBe(newerTabId); + expect(capturedTabId).toBe(olderTabId); }), - ), +); + +it.effect("does not let a no-tab response suppress an earlier tab decision", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const initialTabId = PreviewTabId.make("tab-initial"); + const openedTabId = PreviewTabId.make("tab-opened-late"); + const releaseOpenResponse = yield* Deferred.make(); + const routedRequests: RoutedRequest[] = []; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(requests, (request) => { + routedRequests.push(request); + const marker = + typeof request.input === "object" && request.input !== null && "marker" in request.input + ? request.input.marker + : undefined; + const response = Effect.gen(function* () { + if (marker === "older") { + yield* Deferred.await(releaseOpenResponse); + } + yield* broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: + request.operation === "open" + ? { available: true, tabId: marker === "older" ? openedTabId : initialTabId } + : { url: "http://localhost:3200" }, + }); + if (marker === "newer") { + yield* Deferred.succeed(releaseOpenResponse, undefined); + } + }); + return response.pipe(Effect.forkScoped, Effect.asVoid); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + yield* broker.invoke({ scope, operation: "open", input: {} }); + const older = yield* broker + .invoke({ + scope, + operation: "open", + input: { marker: "older", reuseExistingTab: false }, + }) + .pipe(Effect.forkScoped); + yield* Effect.yieldNow; + const newer = yield* broker + .invoke({ scope, operation: "snapshot", input: { marker: "newer" } }) + .pipe(Effect.forkScoped); + yield* Fiber.join(newer); + yield* Fiber.join(older); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routedRequests.at(-1)?.tabId).toBe(openedTabId); + }), ); it.effect("announces a live replacement stream before delivering requests", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const events = yield* broker.connect(makeHost()); - const receivedTypes: PreviewAutomationStreamEvent["type"][] = []; - const consumer = yield* events.pipe( - Stream.take(2), - Stream.runForEach((event) => { - receivedTypes.push(event.type); - return event.type === "connected" - ? Effect.void - : broker.respond({ - clientId: "client-1", - connectionId: event.connectionId, - requestId: event.request.requestId, - ok: true, - result: "ready", - }); - }), - Effect.forkScoped, - ); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const events = yield* broker.connect(makeHost()); + const receivedTypes: PreviewAutomationStreamEvent["type"][] = []; + const consumer = yield* events.pipe( + Stream.take(2), + Stream.runForEach((event) => { + receivedTypes.push(event.type); + return event.type === "connected" + ? Effect.void + : broker.respond({ + clientId: "client-1", + connectionId: event.connectionId, + requestId: event.request.requestId, + ok: true, + result: "ready", + }); + }), + Effect.forkScoped, + ); + yield* Effect.yieldNow; - const result = yield* broker.invoke({ scope, operation: "status", input: {} }); - yield* Fiber.join(consumer); + const result = yield* broker.invoke({ scope, operation: "status", input: {} }); + yield* Fiber.join(consumer); - expect(receivedTypes).toEqual(["connected", "request"]); - expect(result).toBe("ready"); - }), - ), + expect(receivedTypes).toEqual(["connected", "request"]); + expect(result).toBe("ready"); + }), ); it.effect.each([ @@ -309,101 +301,95 @@ it.effect.each([ message: new PreviewBrowserRootError().message, }, ])("preserves server browser failure guidance ($clientId)", ({ clientId, shown, message }) => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost({ clientId }))); - yield* Stream.runForEach(requests, (request) => - broker.respond({ - clientId, - connectionId: request.connectionId, - requestId: request.requestId, - ok: false, - error: { - _tag: "PreviewAutomationExecutionError", - message, - }, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - const error = yield* broker - .invoke({ scope, operation: "open", input: {} }) - .pipe(Effect.flip); - expect(error._tag).toBe("PreviewAutomationExecutionError"); - expect(error.message.includes(message)).toBe(shown); - }), - ), + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost({ clientId }))); + yield* Stream.runForEach(requests, (request) => + broker.respond({ + clientId, + connectionId: request.connectionId, + requestId: request.requestId, + ok: false, + error: { + _tag: "PreviewAutomationExecutionError", + message, + }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + const error = yield* broker + .invoke({ scope, operation: "open", input: {} }) + .pipe(Effect.flip); + expect(error._tag).toBe("PreviewAutomationExecutionError"); + expect(error.message.includes(message)).toBe(shown); + }), ); it.effect("names the click target that matched nothing when the server browser times out", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID; - const requests = requestsFrom(yield* broker.connect(makeHost({ clientId }))); - yield* Stream.runForEach(requests, (request) => - broker.respond({ - clientId, - connectionId: request.connectionId, - requestId: request.requestId, - ok: false, - error: { - _tag: "PreviewAutomationTimeoutError", - message: "No element matches the target.", - detail: { reason: 'No element matches ".definitely-no-such-t3-target".' }, - }, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID; + const requests = requestsFrom(yield* broker.connect(makeHost({ clientId }))); + yield* Stream.runForEach(requests, (request) => + broker.respond({ + clientId, + connectionId: request.connectionId, + requestId: request.requestId, + ok: false, + error: { + _tag: "PreviewAutomationTimeoutError", + message: "No element matches the target.", + detail: { reason: 'No element matches ".definitely-no-such-t3-target".' }, + }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - const error = yield* broker - .invoke({ - scope, - operation: "click", - input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 }, - }) - .pipe(Effect.flip); + const error = yield* broker + .invoke({ + scope, + operation: "click", + input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 }, + }) + .pipe(Effect.flip); - expect(error._tag).toBe("PreviewAutomationTimeoutError"); - expect(error.message).toBe( - 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".', - ); - }), - ), + expect(error._tag).toBe("PreviewAutomationTimeoutError"); + expect(error.message).toBe( + 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".', + ); + }), ); it.effect("distinguishes malformed remote failures", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => - broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: false, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(requests, (request) => + broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: false, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - const error = yield* broker - .invoke({ scope, operation: "status", input: {}, timeoutMs: 2_000 }) - .pipe(Effect.flip); + const error = yield* broker + .invoke({ scope, operation: "status", input: {}, timeoutMs: 2_000 }) + .pipe(Effect.flip); - expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError); - expect(error).toMatchObject({ - operation: "status", - environmentId: scope.environmentId, - threadId: scope.thread.threadId, - providerSessionId: scope.thread.providerSessionId, - providerInstanceId: scope.thread.providerInstanceId, - clientId: "client-1", - requestId: "preview-0", - timeoutMs: 2_000, - }); - }), - ), + expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError); + expect(error).toMatchObject({ + operation: "status", + environmentId: scope.environmentId, + threadId: scope.thread.threadId, + providerSessionId: scope.thread.providerSessionId, + providerInstanceId: scope.thread.providerInstanceId, + clientId: "client-1", + requestId: "preview-0", + timeoutMs: 2_000, + }); + }), ); it.effect("does not create host state from focus updates without a live stream", () => @@ -424,665 +410,665 @@ it.effect("does not create host state from focus updates without a live stream", ); it.effect("removes host availability when the authoritative request stream disconnects", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - const beforeAcquisition = yield* broker - .invoke({ scope, operation: "status", input: {} }) - .pipe(Effect.flip); - expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError); + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost())); + const beforeAcquisition = yield* broker + .invoke({ scope, operation: "status", input: {} }) + .pipe(Effect.flip); + expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError); - const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Fiber.interrupt(consumer); + const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* Fiber.interrupt(consumer); - const error = yield* broker - .invoke({ scope, operation: "status", input: {} }) - .pipe(Effect.flip); - expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError); - }), - ), + const error = yield* broker + .invoke({ scope, operation: "status", input: {} }) + .pipe(Effect.flip); + expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError); + }), ); it.effect("routes requests for background threads through an environment-level host", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const backgroundThreadId = ThreadId.make("thread-background"); - const requests = requestsFrom(yield* broker.connect(makeHost())); - let routedThreadId: string | undefined; - yield* Stream.runForEach(requests, (request) => { - routedThreadId = request.threadId; - return broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "background", - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const backgroundThreadId = ThreadId.make("thread-background"); + const requests = requestsFrom(yield* broker.connect(makeHost())); + let routedThreadId: string | undefined; + yield* Stream.runForEach(requests, (request) => { + routedThreadId = request.threadId; + return broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "background", + }); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + const result = yield* broker.invoke({ + scope: { + ...scope, + thread: { + ...scope.thread, + threadId: backgroundThreadId, + providerSessionId: "provider-session-background", + }, + }, + operation: "status", + input: {}, + }); + + expect(result).toBe("background"); + expect(routedThreadId).toBe(backgroundThreadId); + }), +); + +it.effect("never routes a provider session to a host from another environment", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const matchingRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-matching" })), + ); + const foreignRequests = requestsFrom( + yield* broker.connect( + makeHost({ + clientId: "client-foreign", + environmentId: EnvironmentId.make("environment-foreign"), + }), + ), + ); + yield* Stream.runForEach(matchingRequests, (request) => + broker.respond({ + clientId: "client-matching", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "matching", + }), + ).pipe(Effect.forkScoped); + yield* Stream.runForEach(foreignRequests, (request) => + broker.respond({ + clientId: "client-foreign", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "foreign", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( + "matching", + ); + }), +); + +it.effect("pins a provider session to its initial host despite later focus changes", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + let firstConnectionId = ""; + let secondConnectionId = ""; + const firstRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-first" })), + (connectionId) => { + firstConnectionId = connectionId; + }, + ); + const secondRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-second" })), + (connectionId) => { + secondConnectionId = connectionId; + }, + ); + yield* Stream.runForEach(firstRequests, (request) => + broker.respond({ + clientId: "client-first", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "first", + }), + ).pipe(Effect.forkScoped); + yield* Stream.runForEach(secondRequests, (request) => + broker.respond({ + clientId: "client-second", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "second", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + yield* broker.focusHost({ + clientId: "client-first", + environmentId: scope.environmentId, + connectionId: "connection-stale", + focused: true, + liveTabs: [{ threadId: scope.thread.threadId, tabId: PreviewTabId.make("stale-tab") }], + }); + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("second"); + yield* broker.focusHost({ + clientId: "client-first", + environmentId: scope.environmentId, + connectionId: firstConnectionId, + focused: true, + }); + + const firstPinnedScope = { + ...scope, + thread: { ...scope.thread, providerSessionId: "provider-session-first-pinned" }, + }; + expect( + yield* broker.invoke({ scope: firstPinnedScope, operation: "status", input: {} }), + ).toBe("first"); + + yield* broker.focusHost({ + clientId: "client-second", + environmentId: scope.environmentId, + connectionId: secondConnectionId, + focused: true, + }); - const result = yield* broker.invoke({ + expect( + yield* broker.invoke({ scope: firstPinnedScope, operation: "status", input: {} }), + ).toBe("first"); + expect( + yield* broker.invoke({ scope: { ...scope, - thread: { - ...scope.thread, - threadId: backgroundThreadId, - providerSessionId: "provider-session-background", - }, + thread: { ...scope.thread, providerSessionId: "provider-session-second-pinned" }, }, operation: "status", input: {}, - }); - - expect(result).toBe("background"); - expect(routedThreadId).toBe(backgroundThreadId); - }), - ), + }), + ).toBe("second"); + }), ); -it.effect("never routes a provider session to a host from another environment", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const matchingRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-matching" })), - ); - const foreignRequests = requestsFrom( - yield* broker.connect( - makeHost({ - clientId: "client-foreign", - environmentId: EnvironmentId.make("environment-foreign"), - }), - ), +it.effect("prefers the live tab owner for new sessions without moving existing leases", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const connections = new Map(); + for (const clientId of ["owner", "other"]) { + const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })), (connectionId) => + connections.set(clientId, connectionId), ); - yield* Stream.runForEach(matchingRequests, (request) => + yield* Stream.runForEach(requests, (request) => broker.respond({ - clientId: "client-matching", + clientId, connectionId: request.connectionId, requestId: request.requestId, ok: true, - result: "matching", + result: clientId, }), ).pipe(Effect.forkScoped); - yield* Stream.runForEach(foreignRequests, (request) => - broker.respond({ - clientId: "client-foreign", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "foreign", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "matching", - ); - }), - ), -); - -it.effect("pins a provider session to its initial host despite later focus changes", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - let firstConnectionId = ""; - let secondConnectionId = ""; - const firstRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-first" })), - (connectionId) => { - firstConnectionId = connectionId; + } + yield* Effect.yieldNow; + yield* broker.focusHost({ + clientId: "owner", + environmentId: scope.environmentId, + connectionId: connections.get("owner")!, + focused: false, + liveTabs: [ + { threadId: scope.thread.threadId, tabId: PreviewTabId.make("signed-in"), visible: true }, + ], + }); + yield* broker.focusHost({ + clientId: "other", + environmentId: scope.environmentId, + connectionId: connections.get("other")!, + focused: true, + liveTabs: [ + { + threadId: scope.thread.threadId, + tabId: PreviewTabId.make("signed-in"), + visible: false, }, - ); - const secondRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-second" })), - (connectionId) => { - secondConnectionId = connectionId; + { + threadId: ThreadId.make("another-thread"), + tabId: PreviewTabId.make("different-tab"), + visible: true, }, - ); - yield* Stream.runForEach(firstRequests, (request) => - broker.respond({ - clientId: "client-first", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "first", - }), - ).pipe(Effect.forkScoped); - yield* Stream.runForEach(secondRequests, (request) => - broker.respond({ - clientId: "client-second", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "second", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.focusHost({ - clientId: "client-first", - environmentId: scope.environmentId, - connectionId: "connection-stale", - focused: true, - liveTabs: [{ threadId: scope.thread.threadId, tabId: PreviewTabId.make("stale-tab") }], - }); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "second", - ); - yield* broker.focusHost({ - clientId: "client-first", - environmentId: scope.environmentId, - connectionId: firstConnectionId, - focused: true, - }); - - const firstPinnedScope = { - ...scope, - thread: { ...scope.thread, providerSessionId: "provider-session-first-pinned" }, - }; - expect( - yield* broker.invoke({ scope: firstPinnedScope, operation: "status", input: {} }), - ).toBe("first"); - - yield* broker.focusHost({ - clientId: "client-second", - environmentId: scope.environmentId, - connectionId: secondConnectionId, - focused: true, - }); - - expect( - yield* broker.invoke({ scope: firstPinnedScope, operation: "status", input: {} }), - ).toBe("first"); - expect( - yield* broker.invoke({ - scope: { - ...scope, - thread: { ...scope.thread, providerSessionId: "provider-session-second-pinned" }, - }, - operation: "status", - input: {}, - }), - ).toBe("second"); - }), - ), -); + ], + }); + expect(yield* broker.invoke({ scope, operation: "evaluate", input: {} })).toBe("owner"); + expect( + yield* broker.invoke({ + scope: { ...scope, thread: { ...scope.thread, providerSessionId: "explicit-owner" } }, + tabId: PreviewTabId.make("signed-in"), + operation: "snapshot", + input: {}, + }), + ).toBe("owner"); + expect( + yield* broker.invoke({ + scope: { ...scope, thread: { ...scope.thread, providerSessionId: "other-tab" } }, + tabId: PreviewTabId.make("different-tab"), + operation: "evaluate", + input: {}, + }), + ).toBe("other"); -it.effect("prefers the live tab owner for new sessions without moving existing leases", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const connections = new Map(); - for (const clientId of ["owner", "other"]) { - const requests = requestsFrom( - yield* broker.connect(makeHost({ clientId })), - (connectionId) => connections.set(clientId, connectionId), - ); - yield* Stream.runForEach(requests, (request) => - broker.respond({ - clientId, - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: clientId, - }), - ).pipe(Effect.forkScoped); - } - yield* Effect.yieldNow; - yield* broker.focusHost({ - clientId: "owner", - environmentId: scope.environmentId, - connectionId: connections.get("owner")!, - focused: false, - liveTabs: [ - { threadId: scope.thread.threadId, tabId: PreviewTabId.make("signed-in"), visible: true }, - ], - }); - yield* broker.focusHost({ - clientId: "other", - environmentId: scope.environmentId, - connectionId: connections.get("other")!, - focused: true, - liveTabs: [ - { - threadId: scope.thread.threadId, - tabId: PreviewTabId.make("signed-in"), - visible: false, - }, - { - threadId: ThreadId.make("another-thread"), - tabId: PreviewTabId.make("different-tab"), - visible: true, - }, - ], - }); - expect(yield* broker.invoke({ scope, operation: "evaluate", input: {} })).toBe( - "owner", - ); - expect( - yield* broker.invoke({ - scope: { ...scope, thread: { ...scope.thread, providerSessionId: "explicit-owner" } }, - tabId: PreviewTabId.make("signed-in"), - operation: "snapshot", - input: {}, - }), - ).toBe("owner"); - expect( - yield* broker.invoke({ - scope: { ...scope, thread: { ...scope.thread, providerSessionId: "other-tab" } }, - tabId: PreviewTabId.make("different-tab"), - operation: "evaluate", - input: {}, - }), - ).toBe("other"); - - yield* broker.focusHost({ - clientId: "owner", - environmentId: scope.environmentId, - connectionId: connections.get("owner")!, - focused: false, - liveTabs: [], - }); - expect(yield* broker.invoke({ scope, operation: "evaluate", input: {} })).toBe( - "owner", - ); - expect( - yield* broker.invoke({ - scope: { ...scope, thread: { ...scope.thread, providerSessionId: "after-tab-closed" } }, - operation: "evaluate", - input: {}, - }), - ).toBe("other"); - }), - ), + yield* broker.focusHost({ + clientId: "owner", + environmentId: scope.environmentId, + connectionId: connections.get("owner")!, + focused: false, + liveTabs: [], + }); + expect(yield* broker.invoke({ scope, operation: "evaluate", input: {} })).toBe("owner"); + expect( + yield* broker.invoke({ + scope: { ...scope, thread: { ...scope.thread, providerSessionId: "after-tab-closed" } }, + operation: "evaluate", + input: {}, + }), + ).toBe("other"); + }), ); it.effect("routes resize to a capable host instead of a newer legacy connection", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const capableRequests = requestsFrom( - yield* broker.connect( - makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }), - ), - ); - const legacyRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-legacy" })), - ); - yield* Stream.runForEach(capableRequests, (request) => - broker.respond({ - clientId: "client-capable", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "capable", - }), - ).pipe(Effect.forkScoped); - yield* Stream.runForEach(legacyRequests, (request) => - broker.respond({ - clientId: "client-legacy", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "legacy", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const capableRequests = requestsFrom( + yield* broker.connect( + makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }), + ), + ); + const legacyRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-legacy" })), + ); + yield* Stream.runForEach(capableRequests, (request) => + broker.respond({ + clientId: "client-capable", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "capable", + }), + ).pipe(Effect.forkScoped); + yield* Stream.runForEach(legacyRequests, (request) => + broker.respond({ + clientId: "client-legacy", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "legacy", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - expect( - yield* broker.invoke({ scope, operation: "resize", input: { mode: "fill" } }), - ).toBe("capable"); - }), - ), + expect( + yield* broker.invoke({ scope, operation: "resize", input: { mode: "fill" } }), + ).toBe("capable"); + }), ); it.effect("does not move a live legacy assignment to another runtime for resize", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const legacyRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-legacy" })), - ); - yield* Stream.runForEach(legacyRequests, (request) => - broker.respond({ - clientId: "client-legacy", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "legacy", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "legacy", - ); - - const capableRequests = requestsFrom( - yield* broker.connect( - makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }), - ), - ); - yield* Stream.runForEach(capableRequests, (request) => - broker.respond({ - clientId: "client-capable", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "capable", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const legacyRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-legacy" })), + ); + yield* Stream.runForEach(legacyRequests, (request) => + broker.respond({ + clientId: "client-legacy", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "legacy", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("legacy"); + + const capableRequests = requestsFrom( + yield* broker.connect( + makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }), + ), + ); + yield* Stream.runForEach(capableRequests, (request) => + broker.respond({ + clientId: "client-capable", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "capable", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - const error = yield* broker - .invoke({ scope, operation: "resize", input: { mode: "fill" } }) - .pipe(Effect.flip); - expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "legacy", - ); - }), - ), + const error = yield* broker + .invoke({ scope, operation: "resize", input: { mode: "fill" } }) + .pipe(Effect.flip); + expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError); + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("legacy"); + }), ); it.effect("ignores stale focus updates for a different environment", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - let firstConnectionId = ""; - const firstRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-first" })), - (connectionId) => { - firstConnectionId = connectionId; - }, - ); - const secondRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-second" })), - ); - yield* Stream.runForEach(firstRequests, (request) => - broker.respond({ - clientId: "client-first", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "first", - }), - ).pipe(Effect.forkScoped); - yield* Stream.runForEach(secondRequests, (request) => - broker.respond({ - clientId: "client-second", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "second", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.focusHost({ + Effect.gen(function* () { + const broker = yield* makeBroker; + let firstConnectionId = ""; + const firstRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-first" })), + (connectionId) => { + firstConnectionId = connectionId; + }, + ); + const secondRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-second" })), + ); + yield* Stream.runForEach(firstRequests, (request) => + broker.respond({ clientId: "client-first", - environmentId: EnvironmentId.make("environment-stale"), - connectionId: firstConnectionId, - focused: true, - }); + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "first", + }), + ).pipe(Effect.forkScoped); + yield* Stream.runForEach(secondRequests, (request) => + broker.respond({ + clientId: "client-second", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "second", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "second", - ); - }), - ), + yield* broker.focusHost({ + clientId: "client-first", + environmentId: EnvironmentId.make("environment-stale"), + connectionId: firstConnectionId, + focused: true, + }); + + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("second"); + }), ); it.effect("fails over a pinned provider session only after its host disconnects", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const firstTabId = PreviewTabId.make("tab-on-first-host"); - let firstConnectionId = ""; - let secondRoutedTabId: PreviewTabId | undefined; - const firstRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-first" })), - (connectionId) => { - firstConnectionId = connectionId; - }, - ); - const secondRequests = requestsFrom( - yield* broker.connect(makeHost({ clientId: "client-second" })), - ); - const firstConsumer = yield* Stream.runForEach(firstRequests, (request) => - broker.respond({ - clientId: "client-first", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first", - }), - ).pipe(Effect.forkScoped); - yield* Stream.runForEach(secondRequests, (request) => { - secondRoutedTabId = request.tabId; - return broker.respond({ - clientId: "client-second", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "second", - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.focusHost({ + Effect.gen(function* () { + const broker = yield* makeBroker; + const firstTabId = PreviewTabId.make("tab-on-first-host"); + let firstConnectionId = ""; + let secondRoutedTabId: PreviewTabId | undefined; + const firstRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-first" })), + (connectionId) => { + firstConnectionId = connectionId; + }, + ); + const secondRequests = requestsFrom( + yield* broker.connect(makeHost({ clientId: "client-second" })), + ); + const firstConsumer = yield* Stream.runForEach(firstRequests, (request) => + broker.respond({ clientId: "client-first", - environmentId: scope.environmentId, - connectionId: firstConnectionId, - focused: true, - liveTabs: [{ threadId: scope.thread.threadId, tabId: firstTabId }], - }); - expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({ - host: "first", - tabId: firstTabId, + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first", + }), + ).pipe(Effect.forkScoped); + yield* Stream.runForEach(secondRequests, (request) => { + secondRoutedTabId = request.tabId; + return broker.respond({ + clientId: "client-second", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "second", }); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - yield* Fiber.interrupt(firstConsumer); - yield* Effect.yieldNow; + yield* broker.focusHost({ + clientId: "client-first", + environmentId: scope.environmentId, + connectionId: firstConnectionId, + focused: true, + liveTabs: [{ threadId: scope.thread.threadId, tabId: firstTabId }], + }); + expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({ + host: "first", + tabId: firstTabId, + }); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "second", - ); - expect(secondRoutedTabId).toBeUndefined(); - }), - ), + yield* Fiber.interrupt(firstConsumer); + yield* Effect.yieldNow; + + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("second"); + expect(secondRoutedTabId).toBeUndefined(); + }), ); it.effect("keeps a replacement stream authoritative when the old stream finalizes", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - let firstConnectionId = ""; - let replacementConnectionId = ""; - const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => { - firstConnectionId = connectionId; - }); - yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + let firstConnectionId = ""; + let replacementConnectionId = ""; + const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => { + firstConnectionId = connectionId; + }); + yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - const replacementRequests = requestsFrom( - yield* broker.connect(makeHost()), - (connectionId) => { - replacementConnectionId = connectionId; - }, - ); - yield* Stream.runForEach(replacementRequests, (request) => - broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "replacement", - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + const replacementRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => { + replacementConnectionId = connectionId; + }); + yield* Stream.runForEach(replacementRequests, (request) => + broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "replacement", + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - expect(replacementConnectionId).not.toBe(firstConnectionId); - const result = yield* broker.invoke({ scope, operation: "status", input: {} }); - expect(result).toBe("replacement"); - }), - ), + expect(replacementConnectionId).not.toBe(firstConnectionId); + const result = yield* broker.invoke({ scope, operation: "status", input: {} }); + expect(result).toBe("replacement"); + }), ); it.effect("does not carry a tab id across a replacement automation stream", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const openedTabId = PreviewTabId.make("tab-first-webcontents"); - const firstRequests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(firstRequests, (request) => - broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: - request.operation === "open" - ? { host: "first", tabId: openedTabId } - : { host: "first" }, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const openedTabId = PreviewTabId.make("tab-first-webcontents"); + const firstRequests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(firstRequests, (request) => + broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: + request.operation === "open" ? { host: "first", tabId: openedTabId } : { host: "first" }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({ - host: "first", - tabId: openedTabId, - }); + expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({ + host: "first", + tabId: openedTabId, + }); - const routedRequests: RoutedRequest[] = []; - const replacementRequests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(replacementRequests, (request) => { - routedRequests.push(request); - return broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "replacement", - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; + const routedRequests: RoutedRequest[] = []; + const replacementRequests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(replacementRequests, (request) => { + routedRequests.push(request); + return broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "replacement", + }); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "replacement", - ); - expect(routedRequests.at(-1)?.tabId).toBeUndefined(); - }), - ), + expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( + "replacement", + ); + expect(routedRequests.at(-1)?.tabId).toBeUndefined(); + }), ); it.effect("fails requests assigned to the stream that is replaced", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runDrain(requests).pipe(Effect.forkScoped); - const pending = yield* broker - .invoke({ scope, operation: "status", input: {} }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Effect.yieldNow; + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runDrain(requests).pipe(Effect.forkScoped); + const pending = yield* broker + .invoke({ scope, operation: "status", input: {} }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Effect.yieldNow; - const replacementRequests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped); + const replacementRequests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped); - const error = yield* Fiber.join(pending); - expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError); - expect(error).toMatchObject({ - operation: "status", - environmentId: scope.environmentId, - threadId: scope.thread.threadId, - providerSessionId: scope.thread.providerSessionId, - providerInstanceId: scope.thread.providerInstanceId, - clientId: "client-1", - requestId: "preview-0", - timeoutMs: 15_000, - }); - }), - ), + const error = yield* Fiber.join(pending); + expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError); + expect(error).toMatchObject({ + operation: "status", + environmentId: scope.environmentId, + threadId: scope.thread.threadId, + providerSessionId: scope.thread.providerSessionId, + providerInstanceId: scope.thread.providerInstanceId, + clientId: "client-1", + requestId: "preview-0", + timeoutMs: 15_000, + }); + }), ); -it.effect("accepts responses only from the host that received the request", () => - Effect.scoped( +it.effect( + "keeps another thread's request alive when one request times out on the shared server browser", + () => Effect.gen(function* () { const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => - Effect.gen(function* () { - yield* broker.respond({ - clientId: "client-foreign", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "foreign", - }); - yield* broker.respond({ - clientId: "client-1", - connectionId: "connection-stale", - requestId: request.requestId, - ok: true, - result: "stale", - }); - yield* broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "owner", - }); - }), - ).pipe(Effect.forkScoped); + const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID; + const delivered = yield* Queue.unbounded(); + const requests = requestsFrom( + yield* broker.connect(makeHost({ clientId }), { preferred: true }), + ); + yield* Stream.runForEach(requests, (request) => Queue.offer(delivered, request)).pipe( + Effect.forkScoped, + ); yield* Effect.yieldNow; + const otherScope = { + ...scope, + requestNamespace: "provider-session-2", + thread: { + threadId: ThreadId.make("thread-2"), + providerSessionId: "provider-session-2", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + }; - const result = yield* broker.invoke({ scope, operation: "status", input: {} }); - expect(result).toBe("owner"); + const otherWait = yield* broker + .invoke({ scope: otherScope, operation: "waitFor", input: {}, timeoutMs: 40_000 }) + .pipe(Effect.result, Effect.forkScoped); + const otherRequest = yield* Queue.take(delivered); + // The browser never answers this one, as when it waits behind the thread's own running action. + const stalled = yield* broker + .invoke({ scope, operation: "evaluate", input: {} }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Queue.take(delivered); + + yield* TestClock.adjust("16 seconds"); + expect((yield* Fiber.join(stalled))._tag).toBe("PreviewAutomationTimeoutError"); + + yield* broker.respond({ + clientId, + connectionId: otherRequest.connectionId, + requestId: otherRequest.requestId, + ok: true, + result: "ready", + }); + expect(yield* Fiber.join(otherWait)).toEqual(Result.succeed("ready")); }), - ), ); -it.effect("keeps each thread's current tab when threads share a provider session", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const routed: Array = []; - const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true })); - yield* Stream.runForEach(requests, (request) => { - routed.push(request); - return broker.respond({ +it.effect("accepts responses only from the host that received the request", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const requests = requestsFrom(yield* broker.connect(makeHost())); + yield* Stream.runForEach(requests, (request) => + Effect.gen(function* () { + yield* broker.respond({ + clientId: "client-foreign", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: "foreign", + }); + yield* broker.respond({ + clientId: "client-1", + connectionId: "connection-stale", + requestId: request.requestId, + ok: true, + result: "stale", + }); + yield* broker.respond({ clientId: "client-1", connectionId: request.connectionId, requestId: request.requestId, ok: true, - result: { tabId: request.tabId ?? `tab-${request.threadId}` }, + result: "owner", }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - // Codex runs every thread of an instance in one provider session. - const otherThread = { - ...scope, - thread: { ...scope.thread, threadId: ThreadId.make("thread-2") }, - }; + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; - yield* broker.invoke({ scope, operation: "open", input: {} }); - yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} }); - yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} }); - - expect(routed.map(({ threadId, tabId }) => [threadId, tabId])).toEqual([ - ["thread-1", undefined], - ["thread-2", undefined], - ["thread-1", "tab-thread-1"], - ["thread-2", "tab-thread-2"], - ]); - expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId); - }), - ), + const result = yield* broker.invoke({ scope, operation: "status", input: {} }); + expect(result).toBe("owner"); + }), +); + +it.effect("keeps each thread's current tab when threads share a provider session", () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const routed: Array = []; + const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true })); + yield* Stream.runForEach(requests, (request) => { + routed.push(request); + return broker.respond({ + clientId: "client-1", + connectionId: request.connectionId, + requestId: request.requestId, + ok: true, + result: { tabId: request.tabId ?? `tab-${request.threadId}` }, + }); + }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + // Codex runs every thread of an instance in one provider session. + const otherThread = { + ...scope, + thread: { ...scope.thread, threadId: ThreadId.make("thread-2") }, + }; + + yield* broker.invoke({ scope, operation: "open", input: {} }); + yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} }); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} }); + + expect(routed.map(({ threadId, tabId }) => [threadId, tabId])).toEqual([ + ["thread-1", undefined], + ["thread-2", undefined], + ["thread-1", "tab-thread-1"], + ["thread-2", "tab-thread-2"], + ]); + expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId); + }), ); diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index 85646d387160d..073cecced051b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -662,7 +662,11 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { // The enclosing operation owns the span for this inline handler. onNone: Effect.fnUntraced(function* () { // Never replay possibly applied actions; slow metadata reads must not evict the host. - if (input.updateCurrentTab !== false) { + // The in-process server browser is shared by every thread and cannot hang its stream. + if ( + input.updateCurrentTab !== false && + connection.clientId !== SERVER_BROWSER_AUTOMATION_CLIENT_ID + ) { yield* disconnect(connection.clientId, connection.queue, true); } return yield* new PreviewAutomationTimeoutError(requestContext); diff --git a/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts b/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts index a45cd3acf9c44..23e7e8c218613 100644 --- a/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts @@ -63,299 +63,294 @@ it.effect.each([ ] as const)( "a delegated child whose task is cancelled $cancel resumes at the reset: $resumed", ({ cancel, cancelStatus, resumed }) => - Effect.scoped( - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("task-cancel-usage-limit"); - // Set while the provider's usage-limit result is already on its way. - let limitInFlight: Effect.Effect = Effect.void; - const turns: Array<{ - readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; - readonly events: Queue.Queue; - }> = []; - const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { - instanceId, - driver, - getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), - planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), - openSession: (input) => - Effect.gen(function* () { - const now = yield* DateTime.now; - const events = yield* Queue.unbounded(); - return { - instanceId, + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("task-cancel-usage-limit"); + // Set while the provider's usage-limit result is already on its way. + let limitInFlight: Effect.Effect = Effect.void; + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (input) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: input.providerSessionId, + providerSession: { + id: input.providerSessionId, driver, - providerSessionId: input.providerSessionId, - providerSession: { - id: input.providerSessionId, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), driver, providerInstanceId: instanceId, - status: "ready", - cwd, - model: modelSelection.model, - capabilities: ClaudeProviderCapabilitiesV2, + providerSessionId: input.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, createdAt: now, updatedAt: now, - lastError: null, - }, - events: Stream.fromQueue(events), - ensureThread: ({ threadId }) => - Effect.succeed({ - id: ProviderThreadId.make(`provider-thread:${threadId}`), + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", driver, - providerInstanceId: instanceId, - providerSessionId: input.providerSessionId, - appThreadId: threadId, - ownerNodeId: null, - nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - createdAt: now, - updatedAt: now, - }), - resumeThread: ({ providerThread }) => Effect.succeed(providerThread), - startTurn: (turn) => - Effect.gen(function* () { - turns.push({ turn, events }); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { - id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), - providerThreadId: turn.providerThread.id, - nodeId: turn.rootNodeId, - runAttemptId: turn.attemptId, - nativeTurnRef: null, - ordinal: turn.providerTurnOrdinal, - status: "running", - startedAt: now, - completedAt: null, - }, - }); - }), - steerTurn: () => Effect.die("unused"), - interruptTurn: () => Effect.suspend(() => limitInFlight), - respondToRuntimeRequest: () => Effect.die("unused"), - readThreadSnapshot: () => Effect.die("unused"), - rollbackThread: () => Effect.die("unused"), - forkThread: () => Effect.die("unused"), - }; - }), - }; - const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter); - const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( - { name: "task-cancel-usage-limit" }, - layerAdapters, - { runEffectWorker: false }, - ); - const layerOrchestration = Layer.merge( - layerOrchestrator, - ThreadManagementService.layer.pipe( - Layer.provide(layerOrchestrator), - Layer.provide(ServerSettings.layerTest()), - Layer.provide( - CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), - ), - ), - ); - const sweeps = new Map>(); - const layerRecovery = UsageLimitRecoveryWorker.layer.pipe( + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.suspend(() => limitInFlight), + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter); + const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( + { name: "task-cancel-usage-limit" }, + layerAdapters, + { runEffectWorker: false }, + ); + const layerOrchestration = Layer.merge( + layerOrchestrator, + ThreadManagementService.layer.pipe( + Layer.provide(layerOrchestrator), + Layer.provide(ServerSettings.layerTest()), Layer.provide( - Layer.mergeAll( - Layer.succeed(Scheduler.Scheduler, { - register: (name: string, work: Effect.Effect) => - Effect.gen(function* () { - const context = yield* Effect.context(); - sweeps.set(name, work.pipe(Effect.provideContext(context), Effect.orDie)); - }), - }), - ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), - ServerSettings.layerTest({ autoResumeLimitedThreads: true }), - ), + CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), ), - ); - const layerTest = Layer.merge( - OrchestratorMcpService.layer.pipe( - Layer.provide(layerClientThreads), - Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), - Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), + ), + ); + const sweeps = new Map>(); + const layerRecovery = UsageLimitRecoveryWorker.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(Scheduler.Scheduler, { + register: (name: string, work: Effect.Effect) => + Effect.gen(function* () { + const context = yield* Effect.context(); + sweeps.set(name, work.pipe(Effect.provideContext(context), Effect.orDie)); + }), + }), + ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ServerSettings.layerTest({ autoResumeLimitedThreads: true }), ), - layerRecovery, - ).pipe( - Layer.provideMerge(layerOrchestration), - Layer.provide( - Layer.mergeAll( - layerAdapters, - Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - ServerSettings.layerTest(), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - NodeServices.layer, - NodeCrypto.layer, - ), + ), + ); + const layerTest = Layer.merge( + OrchestratorMcpService.layer.pipe( + Layer.provide(layerClientThreads), + Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), + Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), + ), + layerRecovery, + ).pipe( + Layer.provideMerge(layerOrchestration), + Layer.provide( + Layer.mergeAll( + layerAdapters, + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + ServerSettings.layerTest(), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + NodeServices.layer, + NodeCrypto.layer, ), - ); + ), + ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const sweep = Effect.andThen( - Effect.suspend(() => sweeps.get("usage-limit-recovery")!), - worker.drain(), + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const sweep = Effect.andThen( + Effect.suspend(() => sweeps.get("usage-limit-recovery")!), + worker.drain(), + ); + const parentThreadId = ThreadId.make("thread:task-cancel-limit-parent"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, ); - const parentThreadId = ThreadId.make("thread:task-cancel-limit-parent"); - const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => - orchestrator.streamDomainEvents.pipe( - Stream.filter(predicate), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - const turnRunning = () => - watch( - (event) => - event.type === "provider-turn.updated" && event.payload.status === "running", - ); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create-parent"), - threadId: parentThreadId, - projectId: ProjectId.make("project:task-cancel-limit"), - title: "Parent", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - const parentRunning = yield* turnRunning(); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("start-parent"), - threadId: parentThreadId, - messageId: MessageId.make("message:start-parent"), - text: "Delegate a review", - attachments: [], - dispatchMode: { type: "start_immediately" }, - createdBy: "user", - creationSource: "web", - }); - yield* worker.drain(); - yield* Fiber.join(parentRunning); + const turnRunning = () => + watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:task-cancel-limit"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* turnRunning(); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate a review", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); - const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; - const childRunning = yield* turnRunning(); - yield* orchestrator.dispatch({ - type: "delegated_task.request", - commandId: CommandId.make("delegate"), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRun.rootNodeId!, - task: "Review the change", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - createdBy: "agent", - creationSource: "mcp", + const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; + const childRunning = yield* turnRunning(); + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the change", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + yield* worker.drain(); + yield* Fiber.join(childRunning); + const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; + const childThreadId = task.childThreadId!; + const child = turns.find((entry) => entry.turn.threadId === childThreadId)!; + const childTurn = (yield* orchestrator.getThreadProjection(childThreadId)) + .providerTurns[0]!; + + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:task-cancel-limit"), + requestNamespace: "provider-session:task-cancel-limit", + thread: { + threadId: parentThreadId, + providerSessionId: "provider-session:task-cancel-limit", + providerInstanceId: instanceId, + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const cancelTask = Effect.gen(function* () { + const result = yield* service.cancelTask(scope, { + taskId: task.id, + clientRequestId: "cancel-task", }); yield* worker.drain(); - yield* Fiber.join(childRunning); - const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; - const childThreadId = task.childThreadId!; - const child = turns.find((entry) => entry.turn.threadId === childThreadId)!; - const childTurn = (yield* orchestrator.getThreadProjection(childThreadId)) - .providerTurns[0]!; + return result.status; + }); - const scope: McpInvocationScope = { - environmentId: EnvironmentId.make("environment:task-cancel-limit"), - requestNamespace: "provider-session:task-cancel-limit", - thread: { - threadId: parentThreadId, - providerSessionId: "provider-session:task-cancel-limit", - providerInstanceId: instanceId, + const now = yield* DateTime.now; + const childFailed = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === child.turn.runId && + event.payload.status === "failed", + ); + const hitLimit = Effect.forEach( + [ + { + type: "provider_turn.updated", + driver, + providerTurn: { ...childTurn, status: "failed", completedAt: now }, }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 1, - }; - const cancelTask = Effect.gen(function* () { - const result = yield* service.cancelTask(scope, { - taskId: task.id, - clientRequestId: "cancel-task", - }); - yield* worker.drain(); - return result.status; - }); - - const now = yield* DateTime.now; - const childFailed = yield* watch( - (event) => - event.type === "run.updated" && - event.payload.id === child.turn.runId && - event.payload.status === "failed", - ); - const hitLimit = Effect.forEach( - [ - { - type: "provider_turn.updated", - driver, - providerTurn: { ...childTurn, status: "failed", completedAt: now }, + { + type: "turn.terminal", + driver, + providerThreadId: childTurn.providerThreadId, + providerTurnId: childTurn.id, + runOrdinal: child.turn.runOrdinal, + failureItemOrdinal: 1, + status: "failed", + failure: { + class: "usage_limit", + message: "Claude usage limit reached.", + code: null, + retryable: null, + resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 1 })), }, - { - type: "turn.terminal", - driver, - providerThreadId: childTurn.providerThreadId, - providerTurnId: childTurn.id, - runOrdinal: child.turn.runOrdinal, - failureItemOrdinal: 1, - status: "failed", - failure: { - class: "usage_limit", - message: "Claude usage limit reached.", - code: null, - retryable: null, - resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 1 })), - }, - threadDisposition: "reusable", - }, - ] satisfies ReadonlyArray, - (event) => Queue.offer(child.events, event), - { discard: true }, - ); - let cancelled: string | null = null; - if (cancel === "as its limit lands") { - limitInFlight = hitLimit; - cancelled = yield* cancelTask; - } else { - yield* hitLimit; - } - yield* Fiber.join(childFailed); - yield* worker.drain(); + threadDisposition: "reusable", + }, + ] satisfies ReadonlyArray, + (event) => Queue.offer(child.events, event), + { discard: true }, + ); + let cancelled: string | null = null; + if (cancel === "as its limit lands") { + limitInFlight = hitLimit; + cancelled = yield* cancelTask; + } else { + yield* hitLimit; + } + yield* Fiber.join(childFailed); + yield* worker.drain(); - // The sweep runs every few seconds, so it arms the child before a parent reacts. - yield* sweep; - if (cancel === "after its limit") cancelled = yield* cancelTask; - assert.equal(cancelled, cancelStatus); + // The sweep runs every few seconds, so it arms the child before a parent reacts. + yield* sweep; + if (cancel === "after its limit") cancelled = yield* cancelTask; + assert.equal(cancelled, cancelStatus); - yield* TestClock.adjust("1 minute"); - yield* sweep; - const childAfter = yield* orchestrator.getThreadProjection(childThreadId); - assert.deepEqual( - childAfter.messages.flatMap((message) => - message.role === "user" ? [message.text] : [], - ), - resumed ? ["Review the change", "Continue where you left off."] : ["Review the change"], - ); - }).pipe(Effect.provide(layerTest)); - }), - ), + yield* TestClock.adjust("1 minute"); + yield* sweep; + const childAfter = yield* orchestrator.getThreadProjection(childThreadId); + assert.deepEqual( + childAfter.messages.flatMap((message) => (message.role === "user" ? [message.text] : [])), + resumed ? ["Review the change", "Continue where you left off."] : ["Review the change"], + ); + }).pipe(Effect.provide(layerTest)); + }), ); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index 0c7290660dc5a..43fbd9ec1f197 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -1,4 +1,7 @@ -import type { ProjectionRecordField } from "../orchestration-v2/ProjectionStore.ts"; +import type { + ProjectionRecordField, + ProjectionRecordFilter, +} from "../orchestration-v2/ProjectionStore.ts"; import { CommandId, OrchestratorMcpFailure, @@ -182,7 +185,7 @@ const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) => export const readThread = Effect.fn("mcp.readThread")(function* < K extends ProjectionRecordField = never, ->(threadId?: ThreadId, fields: ReadonlyArray = []) { +>(threadId?: ThreadId, fields: ReadonlyArray = [], filter?: ProjectionRecordFilter) { const context = yield* readCaller(); const targetId = yield* resolveThreadId(context, threadId); const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable)); @@ -192,6 +195,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* < const projection = yield* context.threads .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, { turnItemTypes: ["user_input_request", "approval_request"], + ...filter, }) .pipe( Effect.mapError((error) => diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index d81e9bdf6db52..ec21b839e0ac3 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -61,6 +61,7 @@ import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapter import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts"; +import type * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; import * as ThreadSearch from "../../orchestration-v2/ThreadSearch.ts"; import * as PreviewBrowser from "../../preview/PreviewBrowser.ts"; import * as ProjectService from "../../project/ProjectService.ts"; @@ -987,6 +988,101 @@ it.effect("requires a projectId to file a scratch thread and returns the moved s ); }); +// A thread read whose runs or messages are bounded by nothing but the thread. +const historyReads = (reads: Array) => { + const record = ( + fields: ReadonlyArray, + filter: ProjectionStore.ProjectionRecordFilter | undefined, + ) => { + if ( + fields.includes("runs") && + filter?.runIds === undefined && + filter?.runStatuses === undefined + ) + reads.push("every run"); + if ( + fields.includes("messages") && + filter?.messageIds === undefined && + filter?.messageRunIds === undefined + ) + reads.push("every message"); + }; + const projection = McpToolAccessTestkit.idleThreadProjection( + McpToolAccessTestkit.liveThreadShell(threadId), + ); + return Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: (_target, fields, filter) => + Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)), + getThreadRecords: (_id, fields, filter) => + Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)), + getMessagesById: () => Effect.succeed(new Map()), + dispatch: () => Effect.succeed({ sequence: 1 } as never), + }); +}; + +it.effect("t3_queue list and read load only the queued runs and their messages", () => { + const reads: Array = []; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const call = (args: Record) => + server + .callTool({ name: "t3_queue", arguments: args }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + yield* call({ action: "list" }); + yield* call({ action: "read", queuedRunId: "run:queued" }); + expect(reads).toEqual([]); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide(historyReads(reads)), + ), + ), + ); +}); + +it.effect("handoff analytics read only the caller's active run and its message", () => { + const reads: Array = []; + const recorded = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + yield* server + .callTool({ + name: "t3_queue", + arguments: { action: "edit", queuedRunId: "run:queued", text: "Edited" }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + yield* Deferred.await(recorded); + expect(reads).toEqual([]); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide(historyReads(reads)), + Layer.provide( + Layer.succeed( + AnalyticsService.AnalyticsService, + AnalyticsService.AnalyticsService.of({ + record: () => Deferred.succeed(recorded, undefined).pipe(Effect.asVoid), + flush: Effect.void, + recordOwners: () => Effect.void, + }), + ), + ), + ), + ), + ); +}); + it.effect("rejects an unknown organize target instead of archiving the calling thread", () => { const dispatched: Array = []; return Effect.gen(function* () { diff --git a/apps/server/src/mcp/toolkits/preview/handlers.test.ts b/apps/server/src/mcp/toolkits/preview/handlers.test.ts index 25eebc0c16f8e..496c9bcb1cdc2 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.test.ts @@ -28,77 +28,75 @@ import { claimPreviewRecording, layerStandard } from "./handlers.ts"; import { PreviewStandardToolkit } from "./tools.ts"; it.effect("preview_open navigates the opened tab to a dev server in one tool call", () => - Effect.scoped( - Effect.gen(function* () { - const scope = yield* McpInvocationContext.McpInvocationContext; - const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; - const connected = yield* Deferred.make(); - const tabId = PreviewTabId.make("opened-tab"); - const target = { - kind: "environment-port" as const, - port: 3000, - path: "/settings?tab=account", - }; - const requests: PreviewAutomationRequest[] = []; - const status = { - available: true, - visible: false, - tabId, - url: "http://localhost:3000/settings?tab=account", - title: "Settings", - loading: false, - }; - const events = yield* broker.connect({ + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; + const connected = yield* Deferred.make(); + const tabId = PreviewTabId.make("opened-tab"); + const target = { + kind: "environment-port" as const, + port: 3000, + path: "/settings?tab=account", + }; + const requests: PreviewAutomationRequest[] = []; + const status = { + available: true, + visible: false, + tabId, + url: "http://localhost:3000/settings?tab=account", + title: "Settings", + loading: false, + }; + const events = yield* broker.connect({ + clientId: "client-1", + environmentId: scope.environmentId, + }); + yield* Stream.runForEach(events, (event) => { + if (event.type === "connected") return Deferred.succeed(connected, undefined); + requests.push(event.request); + return broker.respond({ clientId: "client-1", - environmentId: scope.environmentId, + connectionId: event.connectionId, + requestId: event.request.requestId, + ok: true, + result: event.request.operation === "open" ? { ...status, url: "about:blank" } : status, }); - yield* Stream.runForEach(events, (event) => { - if (event.type === "connected") return Deferred.succeed(connected, undefined); - requests.push(event.request); - return broker.respond({ - clientId: "client-1", - connectionId: event.connectionId, - requestId: event.request.requestId, - ok: true, - result: event.request.operation === "open" ? { ...status, url: "about:blank" } : status, - }); - }).pipe(Effect.forkScoped); - yield* Deferred.await(connected); - const toolkit = yield* PreviewStandardToolkit.pipe( - Effect.provide(McpToolAccess.HandlersLayer.layer(layerStandard)), - ); - const results = yield* toolkit - .handle("preview_open", { - url: "http://localhost:3000", - target, - open: false, - reuseExistingTab: false, - }) - .pipe(Stream.unwrap, Stream.runCollect); - expect(results.at(-1)?.result).toEqual(status); - expect(requests.map(({ operation, input }) => ({ operation, input }))).toEqual([ - { operation: "open", input: { open: false, show: false, reuseExistingTab: false } }, - { operation: "navigate", input: { target } }, - ]); - expect(requests[1]?.tabId).toBe(tabId); - expect(requests[1]?.tabIdExplicit).toBe(true); - }).pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment-1"), - requestNamespace: "provider-session-1", - thread: { - threadId: ThreadId.make("thread-1"), - providerSessionId: "provider-session-1", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["preview"] as const), - issuedAt: 1, - }), - Effect.provide( - Layer.mergeAll(PreviewAutomationBroker.layer, liveThreadsLayer).pipe( - Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), + }).pipe(Effect.forkScoped); + yield* Deferred.await(connected); + const toolkit = yield* PreviewStandardToolkit.pipe( + Effect.provide(McpToolAccess.HandlersLayer.layer(layerStandard)), + ); + const results = yield* toolkit + .handle("preview_open", { + url: "http://localhost:3000", + target, + open: false, + reuseExistingTab: false, + }) + .pipe(Stream.unwrap, Stream.runCollect); + expect(results.at(-1)?.result).toEqual(status); + expect(requests.map(({ operation, input }) => ({ operation, input }))).toEqual([ + { operation: "open", input: { open: false, show: false, reuseExistingTab: false } }, + { operation: "navigate", input: { target } }, + ]); + expect(requests[1]?.tabId).toBe(tabId); + expect(requests[1]?.tabIdExplicit).toBe(true); + }).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment-1"), + requestNamespace: "provider-session-1", + thread: { + threadId: ThreadId.make("thread-1"), + providerSessionId: "provider-session-1", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["preview"] as const), + issuedAt: 1, + }), + Effect.provide( + Layer.mergeAll(PreviewAutomationBroker.layer, liveThreadsLayer).pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), ), ), diff --git a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts index 435ab1cd8b1bc..9aeda8ad13936 100644 --- a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts @@ -27,79 +27,77 @@ it.effect.each([ { name: "project opt-in", globalAccess: false, projectAccess: true }, { name: "project opt-out", globalAccess: true, projectAccess: false }, ])("list and close respect the credential for a $name", ({ globalAccess, projectAccess }) => - Effect.scoped( - Effect.gen(function* () { - const projectId = ProjectId.make("preview-controls-project"); - const threadId = ThreadId.make("preview-controls-thread"); - const settings = { - ...DEFAULT_SERVER_SETTINGS, - enableAgentBrowserAccess: globalAccess, - projectSettingsOverrides: { - [projectId]: { enableAgentBrowserAccess: projectAccess }, - }, - }; - const effective = resolveProjectSettings(settings, projectId).settings; - const scope: McpInvocationContext.McpInvocationScope = { - environmentId: EnvironmentId.make("preview-controls-environment"), - requestNamespace: "preview-controls-provider-session", - thread: { - threadId, - providerSessionId: "preview-controls-provider-session", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []), - issuedAt: 0, - }; - const manager = yield* Preview.make.pipe( - Effect.provide( - Layer.merge( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-preview-controls-" }).pipe( - Layer.provide(NodeServices.layer), - ), - NodeCrypto.layer, + Effect.gen(function* () { + const projectId = ProjectId.make("preview-controls-project"); + const threadId = ThreadId.make("preview-controls-thread"); + const settings = { + ...DEFAULT_SERVER_SETTINGS, + enableAgentBrowserAccess: globalAccess, + projectSettingsOverrides: { + [projectId]: { enableAgentBrowserAccess: projectAccess }, + }, + }; + const effective = resolveProjectSettings(settings, projectId).settings; + const scope: McpInvocationContext.McpInvocationScope = { + environmentId: EnvironmentId.make("preview-controls-environment"), + requestNamespace: "preview-controls-provider-session", + thread: { + threadId, + providerSessionId: "preview-controls-provider-session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []), + issuedAt: 0, + }; + const manager = yield* Preview.make.pipe( + Effect.provide( + Layer.merge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-preview-controls-" }).pipe( + Layer.provide(NodeServices.layer), ), + NodeCrypto.layer, ), - ); - const tab = yield* manager.open({ threadId, url: "http://localhost:3000" }); - const layerDependencies = Layer.mergeAll( - PreviewAutomationBroker.layer.pipe( - Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - Layer.succeed(Preview.PreviewManager, manager), - Layer.succeed(McpInvocationContext.McpInvocationContext, scope), - McpToolAccessTestkit.liveThreadsLayer, - Layer.mock(ServerSettings.ServerSettingsService)({ - getSettings: Effect.succeed(settings), - }), - ); - const toolkit = yield* PreviewControlsToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(PreviewControlsHandlers.layer).pipe( - Layer.provide(layerDependencies), - ), + ), + ); + const tab = yield* manager.open({ threadId, url: "http://localhost:3000" }); + const layerDependencies = Layer.mergeAll( + PreviewAutomationBroker.layer.pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + Layer.succeed(Preview.PreviewManager, manager), + Layer.succeed(McpInvocationContext.McpInvocationContext, scope), + McpToolAccessTestkit.liveThreadsLayer, + Layer.mock(ServerSettings.ServerSettingsService)({ + getSettings: Effect.succeed(settings), + }), + ); + const toolkit = yield* PreviewControlsToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(PreviewControlsHandlers.layer).pipe( + Layer.provide(layerDependencies), ), - ); - const listed = yield* toolkit - .handle("t3_preview_list", {}) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - const closed = yield* toolkit - .handle("t3_preview_close", { tabId: tab.tabId }) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - if (projectAccess) { - expect(listed.at(-1)?.result).toMatchObject({ sessions: [tab], nextCursor: null }); - expect(closed.at(-1)?.result).toEqual({}); - expect((yield* manager.list({ threadId })).sessions).toEqual([]); - } else { - for (const result of [listed, closed]) { - expect(result.at(-1)?.result).toMatchObject({ - _tag: "PreviewAutomationUnavailableError", - capability: "preview", - threadId, - }); - } - expect((yield* manager.list({ threadId })).sessions).toEqual([tab]); + ), + ); + const listed = yield* toolkit + .handle("t3_preview_list", {}) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); + const closed = yield* toolkit + .handle("t3_preview_close", { tabId: tab.tabId }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); + if (projectAccess) { + expect(listed.at(-1)?.result).toMatchObject({ sessions: [tab], nextCursor: null }); + expect(closed.at(-1)?.result).toEqual({}); + expect((yield* manager.list({ threadId })).sessions).toEqual([]); + } else { + for (const result of [listed, closed]) { + expect(result.at(-1)?.result).toMatchObject({ + _tag: "PreviewAutomationUnavailableError", + capability: "preview", + threadId, + }); } - }), - ), + expect((yield* manager.list({ threadId })).sessions).toEqual([tab]); + } + }), ); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index d6c746440a60a..e797d6bcf5c2b 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -537,8 +537,8 @@ describe("pull request toolkit handlers", () => { ]), }); const result = yield* harness.call("list_thread_pull_requests", {}); - expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]); - expect(result.pullRequests[0]).toEqual({ + expect(result.pullRequests.map((entry) => entry.number)).toEqual([1, 2, 3, 10]); + expect(result.pullRequests[2]).toEqual({ host: "github.com", repository: "t3tools/t3code", number: 3, @@ -587,8 +587,8 @@ describe("listThreadPullRequests", () => { ], }); expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([ - [2, { kind: "native", position: 2, size: 2 }], [1, { kind: "native", position: 1, size: 2 }], + [2, { kind: "native", position: 2, size: 2 }], ]); expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]); }); @@ -608,6 +608,58 @@ describe("listThreadPullRequests", () => { ]); expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]); }); + + it("pages a large list once through, with each page's stacks whole", () => { + const thread = { + pullRequests: [ + makeLink(1, { headBranch: "feat-a" }), + ...Array.from({ length: 118 }, (_, index) => makeLink(index + 2)), + makeLink(120, { headBranch: "feat-z", baseBranch: "feat-a" }), + ], + }; + const pages = [listThreadPullRequests(thread)]; + for (let next = pages[0]!.nextCursor; next !== null; next = pages.at(-1)!.nextCursor) { + pages.push(listThreadPullRequests(thread, next)); + } + expect(pages.map((page) => page.pullRequests.length)).toEqual([50, 50, 20]); + expect(pages.flatMap((page) => page.pullRequests.map((entry) => entry.number))).toEqual( + Array.from({ length: 120 }, (_, index) => index + 1), + ); + const stack = { kind: "derived", numbers: [1, 120] }; + expect(pages.map((page) => page.chains.length)).toEqual([50, 50, 20]); + expect(pages.map((page) => page.chains.filter((chain) => chain.numbers.length > 1))).toEqual([ + [stack], + [], + [stack], + ]); + + // Unlinking the first page must not shift the cursor past PRs not yet seen. + const remaining = { pullRequests: thread.pullRequests.slice(50) }; + expect( + listThreadPullRequests(remaining, pages[0]!.nextCursor!).pullRequests.map( + (entry) => entry.number, + ), + ).toEqual(Array.from({ length: 50 }, (_, index) => index + 51)); + }); + + it("filters by state before paging, counting a PR with no known state as open", () => { + const merged = (number: number) => { + const link = makeLink(number, { headBranch: `feat-${number}` }); + return { ...link, snapshot: { ...link.snapshot!, state: "merged" as const } }; + }; + const thread = { + pullRequests: [ + ...Array.from({ length: 50 }, (_, index) => merged(index + 1)), + ...Array.from({ length: 10 }, (_, index) => makeLink(index + 51)), + ], + }; + const open = listThreadPullRequests(thread, undefined, ["open"]); + expect(open.pullRequests.map((entry) => entry.number)).toEqual( + Array.from({ length: 10 }, (_, index) => index + 51), + ); + expect(open.nextCursor).toBeNull(); + expect(listThreadPullRequests(thread, undefined, ["merged"]).nextCursor).toBeNull(); + }); }); describe("pull request guide tools", () => { diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 8983b8e62652d..84e65ce877f69 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1,6 +1,7 @@ import { CommandId, type OrchestrationProjectShell, + type PullRequestState, type OrchestrationV2ThreadShell, type ThreadId, type ThreadPullRequestLink, @@ -72,18 +73,39 @@ function entryOf( }; } +const PULL_REQUEST_LIST_PAGE_SIZE = 50; + +// A total order that survives unlinking: the cursor names a position, not an index, so removing +// PRs already returned cannot skip later ones. PRs linked in one call share `linkedAt`. +function pullRequestListPosition(link: ThreadPullRequestLink): string { + return [link.linkedAt, link.host, link.repository, String(link.number).padStart(10, "0")].join( + " ", + ); +} + export function listThreadPullRequests( thread: Pick, + cursor?: string, + states?: ReadonlyArray, ): ListThreadPullRequestsResult { const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []); + const after = visibleThreadPullRequests(thread.pullRequests ?? []) + .filter((link) => states === undefined || states.includes(link.snapshot?.state ?? "open")) + .map((link) => ({ link, position: pullRequestListPosition(link) })) + .filter(({ position }) => cursor === undefined || position > cursor) + .toSorted((left, right) => (left.position < right.position ? -1 : 1)); + const page = after.slice(0, PULL_REQUEST_LIST_PAGE_SIZE); + const pageKeys = new Set(page.map(({ link }) => threadPullRequestKeyOf(link))); return { - pullRequests: visibleThreadPullRequests(thread.pullRequests ?? []).map((link) => - entryOf(link, chains), - ), - chains: chains.map((chain) => ({ - kind: chain.kind, - numbers: chain.layers.map((layer) => layer.number), - })), + pullRequests: page.map(({ link }) => entryOf(link, chains)), + // Stacks with a pull request on this page, whole. + chains: chains + .filter((chain) => chain.layers.some((layer) => pageKeys.has(threadPullRequestKeyOf(layer)))) + .map((chain) => ({ + kind: chain.kind, + numbers: chain.layers.map((layer) => layer.number), + })), + nextCursor: after.length > page.length ? page.at(-1)!.position : null, }; } @@ -407,7 +429,7 @@ const make = Effect.gen(function* () { ), list_thread_pull_requests: McpToolAccess.reads((input) => requireThread(PullRequestListFailedError, input.threadId).pipe( - Effect.map(listThreadPullRequests), + Effect.map((thread) => listThreadPullRequests(thread, input.cursor, input.states)), ), ), watch_pull_request: writesThread((input) => setWatching(input, true)), diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index fe8959b2d22d3..376817db10079 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -236,6 +236,8 @@ export const ListThreadPullRequestsResult = Schema.Struct({ numbers: Schema.Array(Schema.Int), }), ), + /** Pass as `cursor` for the next page; null on the last page. */ + nextCursor: Schema.NullOr(Schema.String), }); export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type; @@ -255,7 +257,7 @@ const LinkPullRequestTool = Tool.make("link_pull_request", { const LinkPullRequestsTool = Tool.make("link_pull_requests", { description: - "Link several PRs to a thread in one call. Use it instead of one `link_pull_request` per PR. URLs that are not PRs come back in `invalidUrls`.", + "Link several PRs to a thread. Use it instead of one `link_pull_request` per PR. URLs that are not PRs come back in `invalidUrls`.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })), @@ -287,7 +289,7 @@ const UnlinkPullRequestTool = Tool.make("unlink_pull_request", { const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", { description: - "Unlink every PR on a thread whose last known state (as `list_thread_pull_requests` shows) is in `states`, in one call. Use it instead of one `unlink_pull_request` per PR. PRs with no known state stay linked.", + "Unlink a thread's PRs whose last known state is in `states`. Use it instead of one `unlink_pull_request` per PR. PRs with no known state stay linked.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })), @@ -305,10 +307,12 @@ const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", { const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { description: - "List PRs linked to a thread, with last known state and stack order (bottom to top). Call only when you need that list. Never as an end-of-work check.", + "List a thread's PRs, with last known state and stack order (bottom to top). Not an end-of-work check.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })), + states: Schema.optional(Schema.Array(PullRequestState)), + cursor: Schema.optional(Schema.String), }), success: ListThreadPullRequestsResult, failure: PullRequestToolError, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 8833f8e7f0738..9f1c5ef544b30 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -475,7 +475,16 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { (input) => input.action === "list" || input.action === "read", McpToolAccess.reads((input) => Effect.gen(function* () { - const { projection } = yield* readThread(input.threadId, ["runs", "messages"]); + const { threads, projection: queued } = yield* readThread(input.threadId, ["runs"], { + runStatuses: ["queued"], + }); + const messages = yield* threads + .getMessagesById( + queued.thread.id, + queued.runs.map((run) => run.userMessageId), + ) + .pipe(Effect.mapError(unavailable)); + const projection = { runs: queued.runs, messages: [...messages.values()] }; if (input.action === "list") { const runs = queuedRunsInDeliveryOrder(projection); const cursor = input.cursor ?? 0; diff --git a/apps/server/src/observability/DefectReporter.test.ts b/apps/server/src/observability/DefectReporter.test.ts index c749c1a845798..8649c9002f205 100644 --- a/apps/server/src/observability/DefectReporter.test.ts +++ b/apps/server/src/observability/DefectReporter.test.ts @@ -78,6 +78,6 @@ describe("DefectReporter", () => { assert.equal(next, 2); assert.equal(yield* Queue.size(logs), 0); }), - ).pipe(Effect.scoped), + ), ); }); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 55a12ef89db80..1a3c1724b94fa 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -138,6 +138,7 @@ const RPC_AGGREGATES = { [WS_METHODS.pullRequestsInvalidate]: "pull-requests", [WS_METHODS.pullRequestsReportState]: "pull-requests", [WS_METHODS.pullRequestsSubscribeRefreshes]: "pull-requests", + [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: "pull-requests", [WS_METHODS.pullRequestsReviewerCandidates]: "pull-requests", [WS_METHODS.pullRequestsRequestReviewers]: "pull-requests", [WS_METHODS.pullRequestsLabelCandidates]: "pull-requests", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d64c9d4240981..aaaf3371ecbcc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1074,6 +1074,109 @@ const optionValues = (question: OrchestrationV2UserInputQuestion | undefined) => describe("AcpAdapterV2", () => { beforeAll(() => bundleAgents); + it.live("keeps a completed tool's status when its linked ACP terminal streams output", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acp-test-terminal-linked-tool"); + const threadId = ThreadId.make("thread-acp-terminal-linked-tool"); + let notify: Parameters< + AcpSessionRuntime.AcpSessionRuntime["Service"]["handleSessionUpdate"] + >[0]; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + notify = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + const send = (update: EffectAcpSchema.SessionUpdate) => + notify({ sessionId: "mock-session-1", update }); + yield* send({ sessionUpdate: "state_update", state: "running" }); + yield* send({ + sessionUpdate: "terminal_update", + terminalId: "term", + command: "npm run dev", + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "linked", + kind: "execute", + title: "Start dev server", + status: "completed", + content: [{ type: "terminal", terminalId: "term" }], + }); + yield* send({ + sessionUpdate: "terminal_output_chunk", + terminalId: "term", + data: Buffer.from("still running").toString("base64"), + }); + yield* send({ + sessionUpdate: "state_update", + state: "idle", + stopReason: "end_turn", + }); + return { stopReason: "end_turn" as const }; + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-terminal-linked-tool"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + }), + ); + const items = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ).flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === "linked" + ? [event.turnItem] + : [], + ); + const last = items.at(-1); + assert.equal(last?.type === "command_execution" ? last.output : null, "still running"); + assert.deepEqual( + items.map((item) => item.status), + items.map(() => "completed"), + "terminal output must not reopen a tool the agent completed", + ); + }).pipe(Effect.provide(layerTest)), + ); + it.live("reports per-turn usage unavailable on a continuation turn that never prompts", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("acp-test-usage-continuation"); @@ -1191,7 +1294,7 @@ describe("AcpAdapterV2", () => { outputTokens: 30, }); assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () => Effect.gen(function* () { @@ -1288,7 +1391,7 @@ describe("AcpAdapterV2", () => { assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); assert.equal(watchedSessions.length, 2); assert.equal(watchedSessions[0], watchedSessions[1]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("retains returned usage when Stop finalizes before the prompt callback", () => Effect.gen(function* () { @@ -1377,7 +1480,7 @@ describe("AcpAdapterV2", () => { }, ); yield* Deferred.succeed(releaseCompletion, undefined); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("drops a late prompt response that lands after the turn finalized", () => @@ -1503,7 +1606,7 @@ describe("AcpAdapterV2", () => { }); stopCollector = true; yield* Fiber.interrupt(collector); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("keeps usage unavailable for undeclared agents even when they report usage", () => @@ -1571,7 +1674,7 @@ describe("AcpAdapterV2", () => { { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents: false }, ); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live.each(["details", "none"] as const)( @@ -1713,7 +1816,7 @@ describe("AcpAdapterV2", () => { const nextEvents = yield* runTurn(2); const next = nextEvents.at(-1); assert.equal(next?.type === "turn.terminal" ? next.status : undefined, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // Droid 0.243.0 and OpenCode 2.1 pair each choice with an optional free-form companion field. @@ -2055,7 +2158,7 @@ describe("AcpAdapterV2", () => { Stream.runHead, ); assert.equal(Option.getOrThrow(terminal).status, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }); it.live.each(["failed", "recovered", "cancelled"] as const)( @@ -2139,7 +2242,7 @@ describe("AcpAdapterV2", () => { assert.equal(retries.at(-1)?.status, "completed"); assert.equal(retries.at(-1)?.title, "Provider recovered"); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live.each([ @@ -2302,7 +2405,7 @@ describe("AcpAdapterV2", () => { }); assert.equal(switchedModel.textBlockCount, 2); assert.include(switchedModel.prompt, "as composer-2"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live.each(["cancelled", "refusal", "error"] as const)( @@ -2438,7 +2541,7 @@ describe("AcpAdapterV2", () => { yield* runTurn("Continue after the undelivered prompt."), "Continue after the undelivered prompt.", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live( @@ -2467,7 +2570,7 @@ describe("AcpAdapterV2", () => { yield* runTurn("Continue after the focused compact."), "Continue after the focused compact.", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live.each([false, true])( @@ -2510,7 +2613,7 @@ describe("AcpAdapterV2", () => { ), 1, ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live.each([ @@ -2541,7 +2644,7 @@ describe("AcpAdapterV2", () => { ProviderAdapter.ProviderCompactionUnsupportedError, ); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("reapplies a selection after a switch away from it failed partway", () => @@ -2626,7 +2729,7 @@ describe("AcpAdapterV2", () => { ["composer-2"], "the native model was left on B, so the turn on A must set it back first", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // regression: #21499 turns blocked only on T3 thread waits must show as waiting @@ -2757,7 +2860,7 @@ describe("AcpAdapterV2", () => { ); } assert.deepEqual(states, [true, false, true, false]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); const textChunk = ( @@ -2878,6 +2981,19 @@ describe("AcpAdapterV2", () => { ["reasoning", "Thinking more"], ], }, + { + label: "opaque ids differ only in surrounding whitespace", + steps: [answer("answer", "A"), answer(" answer ", "B")], + expected: [ + ["assistant_message", "A"], + ["assistant_message", "B"], + ], + }, + { + label: "a chunk continues a full update with the same whitespace-padded id", + steps: [agentMessage(" answer ", "A"), answer(" answer ", "B")], + expected: [["assistant_message", "AB"]], + }, ] satisfies ReadonlyArray<{ readonly label: string; readonly steps: ReadonlyArray; @@ -2902,7 +3018,7 @@ describe("AcpAdapterV2", () => { assert.equal(new Set(snapshots.map((item) => DateTime.formatIso(item.startedAt!))).size, 1); assert.equal(snapshots.at(-1)?.status, "completed"); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("ignores a text flush scheduled before an ACP segment resumed", () => @@ -2930,7 +3046,7 @@ describe("AcpAdapterV2", () => { ["ABCDE", true], ["ABCDE", false], ]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("starts a new replay message after ACP v2 plan boundaries", () => @@ -3030,7 +3146,7 @@ describe("AcpAdapterV2", () => { snapshot.reasoningMessageIds, snapshot.messages.slice(2).map((message) => message.id), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("persists a bounded subset of streamed root and child tool updates", () => @@ -3199,7 +3315,7 @@ describe("AcpAdapterV2", () => { ); } } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps Devin parent paragraphs intact while projecting native child work", () => @@ -3520,7 +3636,7 @@ describe("AcpAdapterV2", () => { ); assert.equal(parentTools.length, 2); assert.equal(parentTools[0]?.title, "Parent tool finished"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("routes interleaved Copilot subagent output into subagent threads", () => @@ -3715,7 +3831,7 @@ describe("AcpAdapterV2", () => { assert.isFalse( items.some((item) => item.threadId === threadId && item.type === "dynamic_tool"), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps protocol diagnostics off unless a protocol logger is supplied", () => @@ -3798,7 +3914,7 @@ describe("AcpAdapterV2", () => { })); assert.isTrue(explicit.some((e) => e.direction === "incoming" && e.stage === "raw")); assert.isTrue(explicit.some((e) => e.direction === "outgoing")); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("advertises ACP session notices and shows them as system notices", () => @@ -3877,7 +3993,7 @@ describe("AcpAdapterV2", () => { ["before the notice, after the notice"], "a notice neither joins the reply nor splits it", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("projects ACP v2 fidelity updates into first-class orchestration items", () => @@ -4072,7 +4188,7 @@ describe("AcpAdapterV2", () => { afterOmittedPatch.messages.some((message) => message.text === "late authoritative text"), "omitted late message content must preserve the authoritative text", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("projects only the tail of long ACP terminal output", () => @@ -4133,7 +4249,7 @@ describe("AcpAdapterV2", () => { assert.isAtLeast(outputs.length, 2); assert.isAtMost(Math.max(...outputs.map((output) => output.length)), 320 * 1024); assert.equal(outputs.at(-1), fullOutput.slice(-320 * 1024)); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live( @@ -4211,7 +4327,7 @@ describe("AcpAdapterV2", () => { nativeTurnId: "persisted-session:turn:1", }), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("creates a fresh ACP identity when recovering an exhausted target", () => @@ -4301,7 +4417,7 @@ describe("AcpAdapterV2", () => { ); const methods = yield* pollProtocolMethods(protocolEvents); assert.equal(methods.filter((method) => method === "session/new").length, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("preserves new-session fallback when an eager ACP session load is stale", () => @@ -4399,7 +4515,7 @@ describe("AcpAdapterV2", () => { ), }), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("replaces an unexpectedly terminated ACP runtime before the next turn", () => @@ -4471,7 +4587,7 @@ describe("AcpAdapterV2", () => { ); assert.equal(runtimeOrdinalSeen, 2); assert.lengthOf(runtimeInputs, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("fails a prompt its agent leaves silent past the inactivity timeout", () => @@ -4507,7 +4623,7 @@ describe("AcpAdapterV2", () => { assert.include(silent?.failure?.message, "15 minutes"); assert.equal(next?.status, "completed"); assert.lengthOf(harness.natives, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -4545,7 +4661,7 @@ describe("AcpAdapterV2", () => { const [silent, next] = yield* harness.terminals(2); assert.equal(silent?.status, "failed"); assert.equal(next?.status, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("delivers a follow-up the agent rejects while it is still processing", () => @@ -4581,7 +4697,7 @@ describe("AcpAdapterV2", () => { const [delivered] = yield* Fiber.join(followUp); assert.equal(delivered?.status, "completed"); assert.equal(promptCalls, 3); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("sends no more prompts once a follow-up waiting on a busy agent is stopped", () => @@ -4629,7 +4745,7 @@ describe("AcpAdapterV2", () => { yield* Fiber.join(interrupt); assert.equal(terminal?.status, "interrupted"); assert.equal(promptCalls, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("holds the inactivity timeout while the agent waits on an approval", () => @@ -4670,7 +4786,7 @@ describe("AcpAdapterV2", () => { const [approved] = yield* harness.terminals(1); assert.equal(approved?.status, "completed"); assert.lengthOf(harness.natives, 1); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("fails a running prompt once when its agent process exits", () => @@ -4706,7 +4822,7 @@ describe("AcpAdapterV2", () => { assert.notEqual(silent?.providerTurnId, exited?.providerTurnId); assert.equal(next?.status, "completed"); assert.lengthOf(harness.natives, 3); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("does not poll the process ledger while a cgroup lease owns teardown", () => @@ -4803,7 +4919,7 @@ describe("AcpAdapterV2", () => { yield* Scope.close(sessionScope, Exit.void); assert.isFalse(isLive(agentPid!), "closing the session must still tear the agent down"); assert.isFalse(leaseExists, "closing the session must remove the lease"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("negotiates and executes optional native session forks through the ACP runtime", () => @@ -5001,7 +5117,7 @@ describe("AcpAdapterV2", () => { terminalOutput.output, "thread-acp-native-fork-target\nBearer target-thread-token", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -5092,7 +5208,7 @@ describe("AcpAdapterV2", () => { { method: "fs/read_text_file", errorCode: -32601 }, ]); assert.isFalse(yield* fileSystem.exists(probePath)); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("does not turn an unknown permission approval into an execute grant", () => @@ -5219,7 +5335,7 @@ describe("AcpAdapterV2", () => { providerTurnId: pending.runtimeRequest.providerTurnId, }); yield* Fiber.join(turnFiber); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -5390,7 +5506,7 @@ describe("AcpAdapterV2", () => { yield* runtime.interruptTurn({ providerThread, providerTurnId }); yield* Fiber.join(turnFiber); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -5531,7 +5647,7 @@ describe("AcpAdapterV2", () => { }); yield* Fiber.join(turnFiber); assert.deepEqual(outcome, { outcome: "selected", optionId }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("replaces the ACP session and clears conversation state on rollback", () => @@ -5714,7 +5830,7 @@ describe("AcpAdapterV2", () => { assert.lengthOf(prompts, 2); // The mock agent reuses its session id, so only the rollback reset resends these notes. assert.include(prompts[1]?.at(-1)?.text ?? "", ""); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("resends T3 notes after rollback when the replaced runtime's prompt settles late", () => @@ -5842,7 +5958,7 @@ describe("AcpAdapterV2", () => { const replacementPrompt = yield* Deferred.await(replacementPromptText); assert.include(replacementPrompt, "T3 Code interaction mode: Default"); assert.include(replacementPrompt, ""); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("quarantines callbacks from a failed rollback replacement before retrying", () => @@ -5991,7 +6107,7 @@ describe("AcpAdapterV2", () => { status: "running", }); assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("settles a Grok background command that completed before an ACP v2 idle error", () => @@ -6054,7 +6170,7 @@ describe("AcpAdapterV2", () => { command?.type === "turn_item.updated" ? command.turnItem.status : undefined, "completed", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("closes the ACP runtime when the agent never answers session/close", () => @@ -6197,7 +6313,7 @@ describe("AcpAdapterV2", () => { items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"), "command TaskOutput must retain its normal tool frame", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // Grok expands only a leading `/name`, so a picked leading `$name` @@ -6277,7 +6393,7 @@ describe("AcpAdapterV2", () => { assert.isTrue(blocks.some((block) => block.text.includes(sent))); assert.isFalse(blocks.some((block) => block.text.trimStart().startsWith("/"))); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // Command completion must release the turn even when the CLI keeps the prompt RPC and process @@ -6373,7 +6489,7 @@ describe("AcpAdapterV2", () => { items.some((item) => item.nativeItemRef?.nativeId === "kill-command"), "KillTask must retain its normal tool frame", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps an agent's empty-valued default choice selectable", () => @@ -6469,7 +6585,7 @@ describe("AcpAdapterV2", () => { ) .map((event) => rawProtocolRequestParam(event, "value")); assert.deepEqual(sentAgentValues, ["example", ""]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("terminalizes an empty successful foreground Bash tool when the turn completes", () => @@ -6608,7 +6724,7 @@ describe("AcpAdapterV2", () => { Stream.runHead, ); assert.isTrue(Option.isSome(loadAfterRestart)); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("drains native ACP cancellation before admitting the next prompt", () => @@ -6712,7 +6828,7 @@ describe("AcpAdapterV2", () => { ), ); assert.equal(nextTerminal.type === "turn.terminal" && nextTerminal.status, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("cancels pending permission requests while interrupting an ACP turn", () => @@ -6803,7 +6919,7 @@ describe("AcpAdapterV2", () => { ), ); assert.equal(terminal.type, "turn.terminal"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("keeps hard teardown excluded until a permission response is enqueued", () => @@ -6892,7 +7008,7 @@ describe("AcpAdapterV2", () => { yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); yield* Fiber.join(responseFiber); yield* Fiber.join(interruptFiber); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("asks form fields with their fixed choices and answers in the declared types", () => @@ -7011,7 +7127,7 @@ describe("AcpAdapterV2", () => { note: "hi", }, }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("keeps explicit empty selections and checks selection counts", () => @@ -7061,7 +7177,7 @@ describe("AcpAdapterV2", () => { answer: () => ({ all: ["a"], some: ["a"] }), }); assert.deepStrictEqual(requiredOmitted.response, { action: "cancel" }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("answers a field named __proto__ like any other field", () => @@ -7086,7 +7202,7 @@ describe("AcpAdapterV2", () => { action: "accept", content: { ["__proto__"]: "b", name: "hi" }, }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("declines a form whose selection counts the client cannot answer, without asking", () => @@ -7108,7 +7224,7 @@ describe("AcpAdapterV2", () => { assert.isUndefined(questions); assert.deepStrictEqual(response, { action: "decline" }); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("cancels a form whose required answer does not fit, or that is dismissed", () => @@ -7130,7 +7246,7 @@ describe("AcpAdapterV2", () => { answer: () => undefined, }); assert.deepStrictEqual(dismissed.response, { action: "cancel" }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("declines a form with a field it cannot ask for, without asking", () => @@ -7148,7 +7264,7 @@ describe("AcpAdapterV2", () => { }); assert.isUndefined(questions); assert.deepStrictEqual(response, { action: "decline" }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("auto-approves tagged MCP elicitations under full-access policy", () => @@ -7206,7 +7322,7 @@ describe("AcpAdapterV2", () => { assert.isFalse(events.some((event) => event.type === "runtime_request.updated")); assert.isTrue(events.some((event) => event.type === "turn.terminal")); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("fails a held native response acknowledgement before normal session close", () => @@ -7304,7 +7420,7 @@ describe("AcpAdapterV2", () => { assert.include(responseLifecycle, "failed"); yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); yield* Fiber.join(closeFiber); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("treats a second hard Stop as success when the turn is already gone", () => @@ -7393,7 +7509,7 @@ describe("AcpAdapterV2", () => { } } assert.equal(terminal, "interrupted"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -7529,7 +7645,7 @@ describe("AcpAdapterV2", () => { } assert.equal(carriedItemStatus, "completed"); assert.equal(secondTerminalStatus, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -7739,7 +7855,7 @@ describe("AcpAdapterV2", () => { "finalize-window terminal must clear the carryover pin", ); }).pipe(Effect.provideService(Clock.Clock, blockingClock)); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => @@ -7977,7 +8093,7 @@ describe("AcpAdapterV2", () => { "buffered spawn ACK must not create a continuation-owned turn item", ); assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -8268,7 +8384,7 @@ describe("AcpAdapterV2", () => { "queued continuation must drain the wake content after the user run", ); assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -8426,7 +8542,7 @@ describe("AcpAdapterV2", () => { 1, "settled soft steer must not respawn the ACP runtime process", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("preserveRuntimeOnSettledInterrupt does not soften a mid-prompt steering interrupt", () => @@ -8499,7 +8615,7 @@ describe("AcpAdapterV2", () => { assert.fail("mid-prompt steering interrupt must still take the hard teardown path"); } assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("direct Stop quarantine drops late background task mutations from the stopped run", () => @@ -8632,7 +8748,7 @@ describe("AcpAdapterV2", () => { yield* hasPendingBackgroundWork, "direct Stop quarantine must drop residual background task mutations from the stopped run", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -8771,7 +8887,7 @@ describe("AcpAdapterV2", () => { yield* hasPendingBackgroundWork, "wake buffer must not stay non-empty and pin idle release after an already-handled re-report", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps a buffered continuation current when a user turn starts before dispatch", () => @@ -8970,7 +9086,7 @@ describe("AcpAdapterV2", () => { assert.equal(continuationTerminalStatus, "completed"); assert.isTrue(bufferedTextSeen, "continuation must drain the wake buffer after the user run"); assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -9174,7 +9290,7 @@ describe("AcpAdapterV2", () => { 1, "exactly one continuation when the last running task ends post-finalize with kept midTurn marks", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -9535,7 +9651,7 @@ describe("AcpAdapterV2", () => { yield* hasPendingBackgroundWork, "wake buffer must not retain turn-1 or turn-2 in-turn-handled ack residue", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("a wake names work that ended while the previous wake was queued", () => @@ -9679,7 +9795,7 @@ describe("AcpAdapterV2", () => { outcome: "completed", summary: 'Command "sleep b" finished', }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -9897,7 +10013,7 @@ describe("AcpAdapterV2", () => { 1, "duplicate completions must not offer another continuation", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("durably poisons start and resume when required hard teardown is unavailable", () => @@ -9977,7 +10093,7 @@ describe("AcpAdapterV2", () => { .pipe(Effect.exit); if (Exit.isSuccess(resumeExit)) assert.fail("poisoned session must reject resumeThread"); assert.include(Cause.pretty(resumeExit.cause), "session is poisoned"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("holds concurrent startTurn behind successful hard teardown and reloads once", () => @@ -10081,7 +10197,7 @@ describe("AcpAdapterV2", () => { Stream.runHead, ); } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.live("lets a caller abandon Stop while hard teardown stalls, and finishes the teardown", () => @@ -10168,7 +10284,7 @@ describe("AcpAdapterV2", () => { assert.equal(runtimeOrdinalSeen, 2); const replacementMethods = yield* pollProtocolMethods(protocolEvents); assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( @@ -10314,7 +10430,7 @@ describe("AcpAdapterV2", () => { carriedCompleted, "Direct Stop must not carry a stopped subagent into the follow-up run", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 16f94c17e3ce1..70f45bc8a46c0 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -656,7 +656,7 @@ describe("AcpRegistryAdapterV2", () => { answer("session/set_mode", {}), ], storedModePick: "autoEdit", - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("switches a mode config option under its own id", () => @@ -671,7 +671,7 @@ describe("AcpRegistryAdapterV2", () => { answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }), ], storedModePick: "auto", - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); const modelOption = (id: string, currentValue: string, grouped = false) => ({ @@ -801,7 +801,7 @@ describe("AcpRegistryAdapterV2", () => { { models: ["hermes", "auto", "default"], current: "hermes" }, ], ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // Copilot's session/new reports its built-in default, not the model it will run @@ -879,7 +879,7 @@ describe("AcpRegistryAdapterV2", () => { configOptions: [copilotModel("claude-sonnet-5.5"), effort("xhigh")], }), ], - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }, ); @@ -941,7 +941,7 @@ describe("AcpRegistryAdapterV2", () => { }), ] : [], - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }, ); @@ -992,7 +992,7 @@ describe("AcpRegistryAdapterV2", () => { configurations.map((configuration) => configuration?.currentModelId), ["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"], ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect( "fails configuration when an option write errors for a reason other than refusal", @@ -1040,7 +1040,7 @@ describe("AcpRegistryAdapterV2", () => { }, }, ], - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }, ); const modelOptions = [ @@ -1124,7 +1124,7 @@ describe("AcpRegistryAdapterV2", () => { storedModel: model, }); assert.equal(opened.configurations.at(-1)?.currentModelId, "codex"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); }); @@ -1220,7 +1220,7 @@ describe("AcpRegistryAdapterV2", () => { const terminal = completed.at(-1)!; if (terminal.type !== "turn.terminal") throw new Error("Missing fallback terminal"); assert.equal(terminal.status, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); // regression: #26695 cancelling a Copilot prompt kills its background agents @@ -1256,7 +1256,7 @@ describe("AcpRegistryAdapterV2", () => { ...copilot, supportsSteeringByInterruptRestart: true, }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("gives Copilot T3's MCP server over HTTP when it advertises HTTP", () => @@ -1389,7 +1389,7 @@ describe("AcpRegistryAdapterV2", () => { new: stdio("Bearer opened-token"), load: stdio("Bearer rotated-token"), }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("the agent process env names the thread it serves", () => @@ -1468,7 +1468,7 @@ describe("AcpRegistryAdapterV2", () => { assert.equal(agentEnvironment?.T3CODE_THREAD_ID, "thread-acp-registry-thread-env"); assert.equal(agentEnvironment?.T3_ACP_MCP_ENDPOINT, endpoint); assert.equal(agentEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer thread-env-token"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each(["before", "after"] as const)( @@ -1561,7 +1561,7 @@ describe("AcpRegistryAdapterV2", () => { ); } } - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("settles Claude's accepted foreground reply while retaining child output", () => @@ -1765,7 +1765,96 @@ describe("AcpRegistryAdapterV2", () => { ), "autonomous root echoes only signal acceptance", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), + ); + + // Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293); + // its documented foreground-done signal is the opt-in assistant.idle session event. + it.effect("settles Copilot's reply on assistant.idle while an async shell holds the prompt", () => + Effect.gen(function* () { + const sessionId = "copilot-session"; + const sessionEvent = (type: string) => ({ + type: "emit_inbound", + frame: { + kind: "notification", + method: "github.com/copilot/sessionEvent", + params: { sessionId, type, data: {} }, + }, + }); + const update = (sessionUpdate: Record) => + claudeFrames.update(sessionId, sessionUpdate); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Copilot", version: "1.0.110" }, + agentCapabilities: { loadSession: true }, + authMethods: [], + }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/new", params: "" }, + }, + { + type: "emit_inbound", + frame: { kind: "response", method: "session/new", result: { sessionId } }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + // A previous prompt's idle can land before this prompt's turn starts. + sessionEvent("assistant.idle"), + update({ sessionUpdate: "session_info_update", title: "after stale idle" }), + sessionEvent("assistant.turn_start"), + update({ + sessionUpdate: "tool_call", + toolCallId: "shell-1", + title: "sleep 120", + kind: "execute", + status: "completed", + rawInput: { command: "sleep 120", mode: "async", detach: false }, + }), + update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } }), + sessionEvent("assistant.idle"), + update({ sessionUpdate: "session_info_update", title: "after foreground idle" }), + // The shell never exits, so the first session/prompt is never answered. + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + sessionEvent("assistant.turn_start"), + update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "two" } }), + sessionEvent("assistant.idle"), + update({ sessionUpdate: "session_info_update", title: "after second idle" }), + ], + undefined, + false, + "github-copilot-cli", + ); + yield* session.runtime.startTurn(session.turnInput(1)); + const stale = yield* session.throughMarker("after stale idle"); + assert.isFalse(stale.some((event) => event.type === "turn.terminal")); + const foreground = yield* session.throughMarker("after foreground idle"); + const terminal = foreground.find((event) => event.type === "turn.terminal"); + assert.isDefined(terminal, "the run settles once Copilot's foreground work is idle"); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + yield* session.runtime.startTurn(session.turnInput(2)); + const second = yield* session.throughMarker("after second idle"); + const secondTerminal = second.find((event) => event.type === "turn.terminal"); + assert.equal(secondTerminal?.type === "turn.terminal" ? secondTerminal.runOrdinal : null, 2); + }).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -1950,7 +2039,7 @@ describe("AcpRegistryAdapterV2", () => { ), "detached requests are cancelled before turn admission", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("retains streamed child tool output through the generic Devin route", () => @@ -2087,7 +2176,70 @@ describe("AcpRegistryAdapterV2", () => { (event) => event.type === "message.updated" && event.message.text.includes("onetwo"), ), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("replaces streamed root tool output with a later content list", () => + Effect.gen(function* () { + const { update } = claudeFrames; + const text = (value: string) => [{ type: "content", content: { type: "text", text: value } }]; + const session = yield* openClaudeReplaySession([ + ...claudeFrames.open, + ...claudeFrames.prompt(1), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "root-tool", + title: "Stream", + status: "in_progress", + content: text("one"), + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_content_chunk", + toolCallId: "root-tool", + content: { type: "content", content: { type: "text", text: "two" } }, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "root-tool", + status: "completed", + content: text("replacement"), + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_content_chunk", + toolCallId: "root-tool", + content: { type: "content", content: { type: "text", text: "-more" } }, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_content_chunk", + toolCallId: "root-tool", + content: { + type: "diff", + changes: [{ operation: "add", path: "/a.txt" }], + patch: { format: "git_patch", text: "PATCH" }, + }, + }), + claudeMarker("tools complete"), + claudeFrames.idle("end_turn"), + claudeFrames.closeRequest, + claudeFrames.closed, + ]); + yield* session.runtime.startTurn(session.turnInput(1)); + const events = yield* session.throughMarker("tools complete"); + const outputs = events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "root-tool" && + "output" in event.turnItem + ? [event.turnItem.output] + : [], + ); + assert.deepEqual(outputs, [ + text("one"), + text("onetwo"), + text("replacement"), + text("replacement-more"), + { type: "Text", text: "replacement-morePATCH" }, + ]); + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps stopped child tools interrupted when a late output chunk arrives", () => @@ -2194,7 +2346,7 @@ describe("AcpRegistryAdapterV2", () => { assert.deepEqual(tools.at(-1)?.output, [ { type: "content", content: { type: "text", text: "stoppingcancelled" } }, ]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps native child tools interrupted after idle and late output", () => @@ -2234,7 +2386,7 @@ describe("AcpRegistryAdapterV2", () => { assert.deepEqual(tools.at(-1)?.output, [ { type: "content", content: { type: "text", text: "late" } }, ]); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each(["error", "end_turn"])( @@ -2530,7 +2682,7 @@ describe("AcpRegistryAdapterV2", () => { "a new execution does not append the previous execution's text", ); assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("fails active Claude work and releases its children when the process exits", () => @@ -2600,7 +2752,7 @@ describe("AcpRegistryAdapterV2", () => { event.turnItem.status === "interrupted", ), ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect("keeps Claude activity after a refused Stop and closes it on retry", () => @@ -2718,7 +2870,7 @@ describe("AcpRegistryAdapterV2", () => { assert.equal(queuedTerminal.status, "interrupted"); assert.isNull(queuedTerminal.failure); assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -2887,6 +3039,6 @@ describe("AcpRegistryAdapterV2", () => { assert.equal(yield* runTurn(1), "failed"); assert.equal(yield* runTurn(2), "completed"); assert.equal(spawned, restarts ? 2 : 1); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }).pipe(Effect.provide(layerTest)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 7d8223842505c..b281ecc16ab84 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -214,7 +214,7 @@ describe("AntigravityAdapterV2 compaction", () => { assert.isUndefined(session.compactThread); assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals); assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -270,7 +270,7 @@ describe("AntigravityAdapterV2 session open", () => { error._tag === "ProviderAdapterOpenSessionError" && error.requiresSignIn, requiresSignIn, ); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -416,7 +416,7 @@ describe("AntigravityAdapterV2 client file system", () => { context("fs/read_text_file"), ); assert.equal(viaInsideLink.content, "inside"); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -586,7 +586,7 @@ describe("AntigravityAdapterV2 workspace changes", () => { context, ).pipe(Effect.exit); assert.isTrue(Exit.isFailure(fromA), "the previous workspace is no longer readable"); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -866,7 +866,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -1074,7 +1074,7 @@ describe("AntigravityAdapterV2 subagent reads", () => { assert.deepEqual(read("call_missing"), failed); assert.deepEqual(read("call_denied"), failed); assert.deepEqual(read("call_unseen"), failed); - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); @@ -1271,6 +1271,6 @@ describe("AntigravityAdapterV2 session system prompt", () => { assert.notInclude(append, "systemPrompt"); assert.include(sent, ""); } - }).pipe(Effect.provide(layerSession), Effect.scoped), + }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 82aaff0b02a31..e17dec01b3442 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -110,6 +110,7 @@ import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import { ClaudeOrchestratorReplayHarness } from "./ClaudeAdapterV2.testkit.ts"; +import { withInlineContext } from "../ContextHandoffDelivery.ts"; import { provideDeterministicTestRuntime } from "../testkit/DeterministicRuntime.ts"; import { runOrchestratorV2Scenario } from "../testkit/OrchestratorScenario.ts"; import { layerProviderReplay } from "../testkit/ProviderReplayHarness.ts"; @@ -974,131 +975,125 @@ describe("ClaudeAdapterV2 session permissions", () => { describe("ClaudeAdapterV2 Auto-accept edits", () => { it.effect("asks before a command instead of allowing it", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-accept-edits-", - }); - let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"), - open: (input) => - Effect.sync(() => { - openedOptions = input.options; - return { - messages: Stream.never, - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }; - }), - forkSession: () => Effect.die("unused"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "auto-accept-edits", - interactionMode: "default", - cwd: "/workspace", - }); - const threadId = ThreadId.make("thread-claude-accept-edits"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-accept-edits-", + }); + let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"), + open: (input) => + Effect.sync(() => { + openedOptions = input.options; + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "auto-accept-edits", + interactionMode: "default", + cwd: "/workspace", + }); + const threadId = ThreadId.make("thread-claude-accept-edits"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeClaudeTestTurnInput({ threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-accept-edits"), + text: "Run node.", + attachments: [], runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-accept-edits"), - text: "Run node.", - attachments: [], - runtimePolicy, - }), - ); - assert.equal(openedOptions?.permissionMode, "acceptEdits"); - const canUseTool = openedOptions?.canUseTool; - assert.isFunction(canUseTool); + }), + ); + assert.equal(openedOptions?.permissionMode, "acceptEdits"); + const canUseTool = openedOptions?.canUseTool; + assert.isFunction(canUseTool); - const requestEvent = yield* runtime.events.pipe( - Stream.takeUntil( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "approval_request", - ), - Stream.runCollect, - Effect.forkScoped, - ); - const command = { command: "node -e 'console.log(42)'" }; - const decision = yield* Effect.promise(() => - canUseTool!("Bash", command, { - signal: new AbortController().signal, - toolUseID: "tool-bash-accept-edits", - requestId: "request-bash-accept-edits", - description: "Check the Node runtime", - }), - ).pipe(Effect.forkScoped); - const first = yield* Effect.raceFirst( - Fiber.join(requestEvent).pipe( - Effect.map((event) => ({ type: "request", event }) as const), - ), - Fiber.join(decision).pipe( - Effect.map((result) => ({ type: "decision", result }) as const), - ), - ); - assert.equal(first.type, "request", "the command ran without asking"); - if (first.type !== "request") return; - const event = first.event.find((event) => event.type === "runtime_request.updated"); - assert.equal(event?.runtimeRequest.kind, "command"); - const approval = first.event.findLast((event) => event.type === "turn_item.updated"); - assert.equal( - approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined, - command.command, - ); + const requestEvent = yield* runtime.events.pipe( + Stream.takeUntil( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "approval_request", + ), + Stream.runCollect, + Effect.forkScoped, + ); + const command = { command: "node -e 'console.log(42)'" }; + const decision = yield* Effect.promise(() => + canUseTool!("Bash", command, { + signal: new AbortController().signal, + toolUseID: "tool-bash-accept-edits", + requestId: "request-bash-accept-edits", + description: "Check the Node runtime", + }), + ).pipe(Effect.forkScoped); + const first = yield* Effect.raceFirst( + Fiber.join(requestEvent).pipe(Effect.map((event) => ({ type: "request", event }) as const)), + Fiber.join(decision).pipe(Effect.map((result) => ({ type: "decision", result }) as const)), + ); + assert.equal(first.type, "request", "the command ran without asking"); + if (first.type !== "request") return; + const event = first.event.find((event) => event.type === "runtime_request.updated"); + assert.equal(event?.runtimeRequest.kind, "command"); + const approval = first.event.findLast((event) => event.type === "turn_item.updated"); + assert.equal( + approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined, + command.command, + ); - yield* runtime.respondToRuntimeRequest({ - requestId: event!.runtimeRequest.id, - decision: "accept", - }); - assert.equal((yield* Fiber.join(decision))?.behavior, "allow"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* runtime.respondToRuntimeRequest({ + requestId: event!.runtimeRequest.id, + decision: "accept", + }); + assert.equal((yield* Fiber.join(decision))?.behavior, "allow"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1182,33 +1177,31 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { (options?.systemPrompt as { readonly append?: string } | undefined)?.append; it.effect("sends append launch arguments to Claude after the T3 instructions", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" }); - yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n"); - const plain = yield* startTurnWithLaunchArgs("", cwd); - const { exit, opened } = yield* startTurnWithLaunchArgs( - '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement', - cwd, - ); - assert.isTrue(Exit.isSuccess(exit)); - assert.lengthOf(opened, 1); - assert.equal( - appendSystemPrompt(opened[0]), - `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`, - ); - assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]); - assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]); - assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" }); + yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n"); + const plain = yield* startTurnWithLaunchArgs("", cwd); + const { exit, opened } = yield* startTurnWithLaunchArgs( + '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement', + cwd, + ); + assert.isTrue(Exit.isSuccess(exit)); + assert.lengthOf(opened, 1); + assert.equal( + appendSystemPrompt(opened[0]), + `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`, + ); + assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]); + assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]); + assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1219,29 +1212,27 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { `--settings '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}'`, "--settings user-settings.json", ])("merges %s beneath T3's settings", (launchArgs) => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" }); - yield* fileSystem.writeFileString( - NodePath.join(cwd, "user-settings.json"), - '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}', - ); - const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd); - assert.isTrue(Exit.isSuccess(exit)); - assert.deepInclude(opened[0]!.settings, { - skillOverrides: { lint: "off" }, - showThinkingSummaries: true, - }); - assert.isUndefined(opened[0]!.extraArgs?.["settings"]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" }); + yield* fileSystem.writeFileString( + NodePath.join(cwd, "user-settings.json"), + '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}', + ); + const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd); + assert.isTrue(Exit.isSuccess(exit)); + assert.deepInclude(opened[0]!.settings, { + skillOverrides: { lint: "off" }, + showThinkingSummaries: true, + }); + assert.isUndefined(opened[0]!.extraArgs?.["settings"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1260,32 +1251,30 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { assert.include(appendSystemPrompt(options), '{"skillOverrides":{"lint":"off"}}'), ], ] as const)("reads %s from the home directory", ([launchArgs, assertOptions]) => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" }); - const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-cwd-" }); - yield* fileSystem.makeDirectory(NodePath.join(home, ".claude")); - yield* fileSystem.writeFileString( - NodePath.join(home, ".claude", "settings.json"), - '{"skillOverrides":{"lint":"off"}}', - ); - const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd).pipe( - Effect.provideService(HostProcess.HomeDirectory, home), - ); - if (Exit.isFailure(exit)) { - assert.fail(makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message); - } - assert.lengthOf(opened, 1); - assertOptions(opened[0]!); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" }); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-cwd-" }); + yield* fileSystem.makeDirectory(NodePath.join(home, ".claude")); + yield* fileSystem.writeFileString( + NodePath.join(home, ".claude", "settings.json"), + '{"skillOverrides":{"lint":"off"}}', + ); + const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + ); + if (Exit.isFailure(exit)) { + assert.fail(makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message); + } + assert.lengthOf(opened, 1); + assertOptions(opened[0]!); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1335,26 +1324,24 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message, ], ] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" }); - const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd); - assert.lengthOf(opened, 0); - assert.isTrue(Exit.isFailure(exit)); - if (!Exit.isFailure(exit)) return; - assert.equal( - makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message, - expectedMessage(cwd), - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" }); + const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd); + assert.lengthOf(opened, 0); + assert.isTrue(Exit.isFailure(exit)); + if (!Exit.isFailure(exit)) return; + assert.equal( + makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message, + expectedMessage(cwd), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1363,95 +1350,93 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { describe("ClaudeAdapterV2 provider installation gate", () => { it.effect("opens each turn's Claude process inside the installation gate", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const log: Array = []; - const instanceId = ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-" }), - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator: yield* IdAllocator.IdAllocatorV2, - installationGate: ProviderInstallationGate.ProviderInstallationGate.of({ - execute: (gatedInstanceId, effect) => - Effect.sync(() => log.push(`enter ${gatedInstanceId}`)).pipe( - Effect.andThen(effect), - Effect.ensuring(Effect.sync(() => log.push("exit"))), - ), - update: () => Effect.die("unused"), - }), - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-gate"), - open: () => - Effect.sync(() => { - log.push("open query"); - return { - messages: Stream.never, - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }; - }), - forkSession: () => Effect.die("unused"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-cwd-" }), - }); - const threadId = ThreadId.make("thread-claude-gate"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-gate"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const log: Array = []; + const instanceId = ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-" }), + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + installationGate: ProviderInstallationGate.ProviderInstallationGate.of({ + execute: (gatedInstanceId, effect) => + Effect.sync(() => log.push(`enter ${gatedInstanceId}`)).pipe( + Effect.andThen(effect), + Effect.ensuring(Effect.sync(() => log.push("exit"))), + ), + update: () => Effect.die("unused"), + }), + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-gate"), + open: () => + Effect.sync(() => { + log.push("open query"); + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-cwd-" }), + }); + const threadId = ThreadId.make("thread-claude-gate"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-gate"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + assert.deepStrictEqual(log, []); + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-gate"), + text: "Hello", + attachments: [], runtimePolicy, - }); - assert.deepStrictEqual(log, []); - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-gate"), - text: "Hello", - attachments: [], - runtimePolicy, - }), - ); + }), + ); - assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -1750,189 +1735,154 @@ describe("ClaudeAdapterV2 resumeThread", () => { describe("ClaudeAdapterV2 resume compaction", () => { it.effect("resolves and cancels the SDK resume dialog through structured runtime input", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-resume-", - }); - let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-resume"), - open: (input) => - Effect.sync(() => { - openedOptions = input.options; - return { - messages: Stream.never, - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }; - }), - forkSession: () => Effect.die("unused"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-resume"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-resume"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-resume-", + }); + let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-resume"), + open: (input) => + Effect.sync(() => { + openedOptions = input.options; + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-resume"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-resume"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeClaudeTestTurnInput({ threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-resume"), - text: "continue", - attachments: [], - }), - ); - const callback = openedOptions?.onUserDialog; - assert.isFunction(callback); - const canUseTool = openedOptions?.canUseTool; - assert.isFunction(canUseTool); - const shellSafetyReason = - "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed"; - for (const [safetyIndex, { askRule, reason }] of [ - { askRule: false, reason: shellSafetyReason }, - { askRule: true, reason: shellSafetyReason }, - { - askRule: false, - reason: - "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.", - }, - { askRule: false, reason: "This shell -c script runs rm and could not be checked" }, - { askRule: false, reason: "A permission rule denies a command in this shell -c script" }, - ].entries()) { - const safetyRequest = yield* runtime.events.pipe( - Stream.filter((event) => event.type === "runtime_request.updated"), - Stream.runHead, - Effect.forkScoped, - ); - const safetySignal = yield* Effect.abortSignal; - const safetyDecision = yield* Effect.promise(() => - canUseTool!( - "Bash", - { command: "for pair in a b; do echo $pair; done" }, - { - signal: safetySignal, - toolUseID: `tool-shell-safety-${safetyIndex}`, - requestId: `request-shell-safety-${safetyIndex}`, - decisionReason: `\u001b[33m${reason}\u001b[39m`, - suppressAlwaysAllowRule: true, - ...(askRule - ? { - matchedAskRule: { - source: "userSettings" as const, - toolName: "Bash", - ruleContent: "*", - }, - } - : {}), - }, - ), - ).pipe(Effect.forkScoped); - const safety = yield* Effect.raceFirst( - Fiber.join(safetyDecision).pipe( - Effect.map((result) => ({ type: "decision", result }) as const), - ), - Fiber.join(safetyRequest).pipe( - Effect.map((event) => ({ type: "approval", event }) as const), - ), - ); - assert.equal(safety.type, askRule ? "approval" : "decision"); - if (safety.type === "decision") { - assert.equal(safety.result?.behavior, "deny"); - if (safety.result?.behavior === "deny") { - assert.include(safety.result.message, reason); - assert.notInclude(safety.result.message, "\u001b["); - } - } else if ( - Option.isSome(safety.event) && - safety.event.value.type === "runtime_request.updated" - ) { - yield* runtime.respondToRuntimeRequest({ - requestId: safety.event.value.runtimeRequest.id, - decision: "decline", - }); - assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny"); - } - yield* Fiber.interrupt(safetyRequest); - } - const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`; - const questionRequestEvent = yield* runtime.events.pipe( + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-resume"), + text: "continue", + attachments: [], + }), + ); + const callback = openedOptions?.onUserDialog; + assert.isFunction(callback); + const canUseTool = openedOptions?.canUseTool; + assert.isFunction(canUseTool); + const shellSafetyReason = + "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed"; + for (const [safetyIndex, { askRule, reason }] of [ + { askRule: false, reason: shellSafetyReason }, + { askRule: true, reason: shellSafetyReason }, + { + askRule: false, + reason: + "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.", + }, + { askRule: false, reason: "This shell -c script runs rm and could not be checked" }, + { askRule: false, reason: "A permission rule denies a command in this shell -c script" }, + ].entries()) { + const safetyRequest = yield* runtime.events.pipe( Stream.filter((event) => event.type === "runtime_request.updated"), Stream.runHead, Effect.forkScoped, ); - const questionResult = yield* Effect.promise(() => + const safetySignal = yield* Effect.abortSignal; + const safetyDecision = yield* Effect.promise(() => canUseTool!( - "AskUserQuestion", - { - questions: [ - { - header: "Target", - question: longQuestion, - options: [ - { label: "Production", description: "Deploy to production." }, - { label: "Staging", description: "Deploy to staging." }, - ], - multiSelect: true, - }, - ], - }, + "Bash", + { command: "for pair in a b; do echo $pair; done" }, { - signal: new AbortController().signal, - toolUseID: "tool-question-full-access", - requestId: "request-question-full-access", + signal: safetySignal, + toolUseID: `tool-shell-safety-${safetyIndex}`, + requestId: `request-shell-safety-${safetyIndex}`, + decisionReason: `\u001b[33m${reason}\u001b[39m`, + suppressAlwaysAllowRule: true, + ...(askRule + ? { + matchedAskRule: { + source: "userSettings" as const, + toolName: "Bash", + ruleContent: "*", + }, + } + : {}), }, ), ).pipe(Effect.forkScoped); - const questionEvent = yield* Fiber.join(questionRequestEvent); - assert.isTrue(Option.isSome(questionEvent)); - if ( - Option.isNone(questionEvent) || - questionEvent.value.type !== "runtime_request.updated" + const safety = yield* Effect.raceFirst( + Fiber.join(safetyDecision).pipe( + Effect.map((result) => ({ type: "decision", result }) as const), + ), + Fiber.join(safetyRequest).pipe( + Effect.map((event) => ({ type: "approval", event }) as const), + ), + ); + assert.equal(safety.type, askRule ? "approval" : "decision"); + if (safety.type === "decision") { + assert.equal(safety.result?.behavior, "deny"); + if (safety.result?.behavior === "deny") { + assert.include(safety.result.message, reason); + assert.notInclude(safety.result.message, "\u001b["); + } + } else if ( + Option.isSome(safety.event) && + safety.event.value.type === "runtime_request.updated" ) { - return; + yield* runtime.respondToRuntimeRequest({ + requestId: safety.event.value.runtimeRequest.id, + decision: "decline", + }); + assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny"); } - yield* runtime.respondToRuntimeRequest({ - requestId: questionEvent.value.runtimeRequest.id, - answers: { [longQuestion]: ["Production", "Staging"] }, - }); - assert.deepEqual(yield* Fiber.join(questionResult), { - behavior: "allow", - updatedInput: { + yield* Fiber.interrupt(safetyRequest); + } + const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`; + const questionRequestEvent = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "runtime_request.updated"), + Stream.runHead, + Effect.forkScoped, + ); + const questionResult = yield* Effect.promise(() => + canUseTool!( + "AskUserQuestion", + { questions: [ { header: "Target", @@ -1944,90 +1894,120 @@ describe("ClaudeAdapterV2 resume compaction", () => { multiSelect: true, }, ], - answers: { [longQuestion]: "Production, Staging" }, }, - toolUseID: "tool-question-full-access", - }); - const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`; - const proposedPlanEvent = yield* runtime.events.pipe( - Stream.filter((event) => event.type === "plan.updated"), - Stream.runHead, - Effect.forkScoped, - ); - const exitPlanResult = yield* Effect.promise(() => - canUseTool!( - "ExitPlanMode", - { plan: longPlan }, + { + signal: new AbortController().signal, + toolUseID: "tool-question-full-access", + requestId: "request-question-full-access", + }, + ), + ).pipe(Effect.forkScoped); + const questionEvent = yield* Fiber.join(questionRequestEvent); + assert.isTrue(Option.isSome(questionEvent)); + if (Option.isNone(questionEvent) || questionEvent.value.type !== "runtime_request.updated") { + return; + } + yield* runtime.respondToRuntimeRequest({ + requestId: questionEvent.value.runtimeRequest.id, + answers: { [longQuestion]: ["Production", "Staging"] }, + }); + assert.deepEqual(yield* Fiber.join(questionResult), { + behavior: "allow", + updatedInput: { + questions: [ { - signal: new AbortController().signal, - toolUseID: "tool-exit-plan-full-access", - requestId: "request-exit-plan-full-access", + header: "Target", + question: longQuestion, + options: [ + { label: "Production", description: "Deploy to production." }, + { label: "Staging", description: "Deploy to staging." }, + ], + multiSelect: true, }, - ), - ); - assert.deepEqual(exitPlanResult, { - behavior: "deny", - message: - "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", - toolUseID: "tool-exit-plan-full-access", - }); - const planEvent = yield* Fiber.join(proposedPlanEvent); - assert.isTrue(Option.isSome(planEvent)); - if (Option.isSome(planEvent) && planEvent.value.type === "plan.updated") { - assert.equal(planEvent.value.plan.kind, "proposed_plan"); - if (planEvent.value.plan.kind === "proposed_plan") { - assert.equal(planEvent.value.plan.markdown, longPlan.trim()); - } + ], + answers: { [longQuestion]: "Production, Staging" }, + }, + toolUseID: "tool-question-full-access", + }); + const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`; + const proposedPlanEvent = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "plan.updated"), + Stream.runHead, + Effect.forkScoped, + ); + const exitPlanResult = yield* Effect.promise(() => + canUseTool!( + "ExitPlanMode", + { plan: longPlan }, + { + signal: new AbortController().signal, + toolUseID: "tool-exit-plan-full-access", + requestId: "request-exit-plan-full-access", + }, + ), + ); + assert.deepEqual(exitPlanResult, { + behavior: "deny", + message: + "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", + toolUseID: "tool-exit-plan-full-access", + }); + const planEvent = yield* Fiber.join(proposedPlanEvent); + assert.isTrue(Option.isSome(planEvent)); + if (Option.isSome(planEvent) && planEvent.value.type === "plan.updated") { + assert.equal(planEvent.value.plan.kind, "proposed_plan"); + if (planEvent.value.plan.kind === "proposed_plan") { + assert.equal(planEvent.value.plan.markdown, longPlan.trim()); } - const requestEvent = yield* runtime.events.pipe( - Stream.filter((event) => event.type === "runtime_request.updated"), - Stream.runHead, - Effect.forkScoped, - ); - const signal = yield* Effect.abortSignal; - const dialog = yield* Effect.promise(() => + } + const requestEvent = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "runtime_request.updated"), + Stream.runHead, + Effect.forkScoped, + ); + const signal = yield* Effect.abortSignal; + const dialog = yield* Effect.promise(() => + callback!( + { + dialogKind: "resume_return", + payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, + }, + { signal, requestId: "dialog-resume-1" }, + ), + ).pipe(Effect.forkScoped); + const event = yield* Fiber.join(requestEvent); + assert.isTrue(Option.isSome(event)); + if (Option.isNone(event) || event.value.type !== "runtime_request.updated") return; + const question = formatClaudeResumeCompactionQuestion({ + ageMinutes: 90, + estimatedTokens: 120000, + }); + yield* runtime.respondToRuntimeRequest({ + requestId: event.value.runtimeRequest.id, + answers: { [question]: "Compact and continue" }, + }); + assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" }); + + assert.deepEqual( + yield* Effect.promise(() => callback!( { dialogKind: "resume_return", payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, }, - { signal, requestId: "dialog-resume-1" }, - ), - ).pipe(Effect.forkScoped); - const event = yield* Fiber.join(requestEvent); - assert.isTrue(Option.isSome(event)); - if (Option.isNone(event) || event.value.type !== "runtime_request.updated") return; - const question = formatClaudeResumeCompactionQuestion({ - ageMinutes: 90, - estimatedTokens: 120000, - }); - yield* runtime.respondToRuntimeRequest({ - requestId: event.value.runtimeRequest.id, - answers: { [question]: "Compact and continue" }, - }); - assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" }); - - assert.deepEqual( - yield* Effect.promise(() => - callback!( - { - dialogKind: "resume_return", - payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, - }, - { signal: AbortSignal.abort(), requestId: "dialog-resume-2" }, - ), - ), - { behavior: "cancelled" }, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + { signal: AbortSignal.abort(), requestId: "dialog-resume-2" }, ), ), + { behavior: "cancelled" }, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), ); @@ -2092,555 +2072,543 @@ describe("ClaudeAdapterV2 attachments", () => { ])( "preserves $name with native PDFs, images, and paths on sends and steering", ({ prompt, expectedText, command, ultrathink, resumed, budget }) => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const claudeHome = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-skills-home-", - }); - yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), { - recursive: true, - }); - yield* fileSystem.writeFileString( - path.join(claudeHome, "skills", "implement", "SKILL.md"), - "---\ndescription: Implement the requested change\n---\nImplement it.\n", - ); - const modelSelection = { - ...CLAUDE_TEST_MODEL_SELECTION, - options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [], - }; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-attachments-", - }); - const offeredMessages: Array = []; - let failOpen = false; - let failOffer = false; - let cancelAfterQueue = false; - const queued = yield* Deferred.make(); - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome }, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-attachments"), - open: () => - Effect.gen(function* () { - if (failOpen) { - failOpen = false; - return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "open", - cause: "rejected open", - }); - } - const messages = yield* Queue.unbounded(); - return { - messages: Stream.fromQueue(messages), - offer: (message, onQueued) => - Effect.suspend(() => { - if (failOffer) { - failOffer = false; - return Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "offer", - cause: "rejected offer", - }), - ); - } - return Effect.sync(() => { - offeredMessages.push(message); - onQueued?.(); - }).pipe( - Effect.andThen(() => - cancelAfterQueue - ? Deferred.succeed(queued, undefined).pipe( - Effect.andThen(Effect.never), - ) - : Effect.void, - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const claudeHome = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-skills-home-", + }); + yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(claudeHome, "skills", "implement", "SKILL.md"), + "---\ndescription: Implement the requested change\n---\nImplement it.\n", + ); + const modelSelection = { + ...CLAUDE_TEST_MODEL_SELECTION, + options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [], + }; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-attachments-", + }); + const offeredMessages: Array = []; + let failOpen = false; + let failOffer = false; + let cancelAfterQueue = false; + const queued = yield* Deferred.make(); + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome }, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-attachments"), + open: () => + Effect.gen(function* () { + if (failOpen) { + failOpen = false; + return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "open", + cause: "rejected open", + }); + } + const messages = yield* Queue.unbounded(); + return { + messages: Stream.fromQueue(messages), + offer: (message, onQueued) => + Effect.suspend(() => { + if (failOffer) { + failOffer = false; + return Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "offer", + cause: "rejected offer", + }), ); - }), - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(messages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-attachments"); - const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ + } + return Effect.sync(() => { + offeredMessages.push(message); + onQueued?.(); + }).pipe( + Effect.andThen(() => + cancelAfterQueue + ? Deferred.succeed(queued, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.void, + ), + ); + }), + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(messages), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-attachments"); + const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const attachment = ChatImageAttachment.make({ + type: "image", + id: ChatAttachmentId.make( + "thread-claude-attachments-12345678-1234-1234-1234-123456789abc", + ), + name: "diagram.png", + mimeType: "image/png", + sizeBytes: 4, + }); + const document = ChatFileAttachment.make({ + type: "file", + id: ChatAttachmentId.make( + "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc", + ), + name: "requirements.pdf", + mimeType: "application/pdf", + sizeBytes: 4, + }); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(attachment)!), + Uint8Array.from([1, 2, 3, 4]), + ); + const pdfBytes = Buffer.from( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF", + ); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(document)!), + pdfBytes, + ); + const attemptId = RunAttemptId.make("attempt-claude-attachments"); + const now = yield* DateTime.now; + + const turnInput = { + ...makeClaudeTestTurnInput({ threadId, + providerThread, + now, + attemptId, modelSelection, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const attachment = ChatImageAttachment.make({ - type: "image", - id: ChatAttachmentId.make( - "thread-claude-attachments-12345678-1234-1234-1234-123456789abc", - ), - name: "diagram.png", - mimeType: "image/png", - sizeBytes: 4, - }); - const document = ChatFileAttachment.make({ - type: "file", - id: ChatAttachmentId.make( - "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc", - ), - name: "requirements.pdf", - mimeType: "application/pdf", - sizeBytes: 4, - }); - yield* fileSystem.writeFile( - path.join(attachmentsDir, attachmentRelativePath(attachment)!), - Uint8Array.from([1, 2, 3, 4]), - ); - const pdfBytes = Buffer.from( - "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF", + text: prompt, + attachments: resumed ? [attachment] : [attachment, document], + }), + nativeThreadHasTurns: resumed, + }; + if (budget === "cancelled-send" || budget === "cancelled-steer") { + const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); + const pages = Buffer.from( + `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`, ); yield* fileSystem.writeFile( - path.join(attachmentsDir, attachmentRelativePath(document)!), - pdfBytes, + documentPath, + Buffer.concat([ + pages, + Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32), + Buffer.from("%%EOF"), + ]), ); - const attemptId = RunAttemptId.make("attempt-claude-attachments"); - const now = yield* DateTime.now; - - const turnInput = { - ...makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId, - modelSelection, - text: prompt, - attachments: resumed ? [attachment] : [attachment, document], - }), - nativeThreadHasTurns: resumed, - }; - if (budget === "cancelled-send" || budget === "cancelled-steer") { + const message = { ...turnInput.message, attachments: [document] }; + if (budget === "cancelled-steer") { + yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } }); + } + const deliver = + budget === "cancelled-send" + ? runtime.startTurn({ ...turnInput, message }) + : runtime.steerTurn({ + threadId, + runId: turnInput.runId, + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message, + }); + cancelAfterQueue = true; + const delivering = yield* deliver.pipe(Effect.forkChild); + yield* Deferred.await(queued); + yield* Fiber.interrupt(delivering); + const delivered = offeredMessages.at(-1)!.message.content; + assert.include(JSON.stringify(delivered), '"type":"document"'); + cancelAfterQueue = false; + if (budget === "cancelled-send") { + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + }); + } + yield* deliver; + const retried = offeredMessages.at(-1)!.message.content; + assert.notInclude(JSON.stringify(retried), '"type":"document"'); + assert.include(JSON.stringify(retried), JSON.stringify(documentPath).slice(1, -1)); + assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000); + return; + } + if (budget !== "none") { + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!); + // The on-disk length deliberately disagrees with sizeBytes. + yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024)); + if (["later-images", "partial-images"].includes(budget)) { const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - const pages = Buffer.from( - `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`, - ); yield* fileSystem.writeFile( documentPath, Buffer.concat([ - pages, - Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32), + pdfBytes.subarray(0, -5), + Buffer.alloc( + (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length, + 32, + ), Buffer.from("%%EOF"), ]), ); - const message = { ...turnInput.message, attachments: [document] }; - if (budget === "cancelled-steer") { - yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } }); - } - const deliver = - budget === "cancelled-send" - ? runtime.startTurn({ ...turnInput, message }) - : runtime.steerTurn({ - threadId, - runId: turnInput.runId, - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }), - message, - }); - cancelAfterQueue = true; - const delivering = yield* deliver.pipe(Effect.forkChild); - yield* Deferred.await(queued); - yield* Fiber.interrupt(delivering); - const delivered = offeredMessages.at(-1)!.message.content; - assert.include(JSON.stringify(delivered), '"type":"document"'); - cancelAfterQueue = false; - if (budget === "cancelled-send") { - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }), - }); - } - yield* deliver; - const retried = offeredMessages.at(-1)!.message.content; - assert.notInclude(JSON.stringify(retried), '"type":"document"'); - assert.include(JSON.stringify(retried), JSON.stringify(documentPath).slice(1, -1)); - assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000); - return; - } - if (budget !== "none") { - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, + yield* runtime.startTurn({ + ...turnInput, + message: { ...turnInput.message, attachments: [document] }, }); - const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!); - // The on-disk length deliberately disagrees with sizeBytes. - yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024)); - if (["later-images", "partial-images"].includes(budget)) { - const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - yield* fileSystem.writeFile( - documentPath, - Buffer.concat([ - pdfBytes.subarray(0, -5), - Buffer.alloc( - (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length, - 32, - ), - Buffer.from("%%EOF"), - ]), - ); - yield* runtime.startTurn({ - ...turnInput, - message: { ...turnInput.message, attachments: [document] }, - }); - assert.include( - JSON.stringify(offeredMessages[0]!.message.content), - '"type":"document"', - ); - const message = { ...turnInput.message, attachments: [attachment, attachment] }; - yield* runtime.interruptTurn({ providerThread, providerTurnId }); - const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later"); - yield* runtime.startTurn({ - ...turnInput, - attemptId: laterAttemptId, - providerTurnOrdinal: 2, - nativeThreadHasTurns: true, - message, - }); - const sent = offeredMessages.at(-1)!.message.content; - assert.isArray(sent); - assert.lengthOf( - typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"), - budget === "partial-images" ? 1 : 0, - ); - assert.include(JSON.stringify(sent), JSON.stringify(imagePath).slice(1, -1)); - yield* runtime.steerTurn({ - threadId, - runId: RunId.make("run-claude-attachments"), - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${laterAttemptId}`, - }), - message, - }); - const steered = offeredMessages.at(-1)!.message.content; - assert.isArray(steered); - assert.lengthOf( - typeof steered === "string" - ? [] - : steered.filter((block) => block.type === "image"), - 0, - ); - assert.include(JSON.stringify(steered), JSON.stringify(imagePath).slice(1, -1)); - assert.isBelow( - Buffer.byteLength( - JSON.stringify(offeredMessages.map((message) => message.message)), - ), - 32_000_000, - ); - return; - } - if (budget === "retained-documents") { - yield* fileSystem.writeFile( - path.join(attachmentsDir, attachmentRelativePath(document)!), - Buffer.concat([ - pdfBytes.subarray(0, pdfBytes.length - 5), - Buffer.alloc(10 * 1024 * 1024, 32), - Buffer.from("%%EOF"), - ]), - ); - } + assert.include( + JSON.stringify(offeredMessages[0]!.message.content), + '"type":"document"', + ); + const message = { ...turnInput.message, attachments: [attachment, attachment] }; + yield* runtime.interruptTurn({ providerThread, providerTurnId }); + const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later"); yield* runtime.startTurn({ ...turnInput, - message: { - ...turnInput.message, - text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt, - attachments: - budget === "retained-text" - ? [] - : budget === "retained-documents" - ? [document] - : [attachment, attachment], - }, + attemptId: laterAttemptId, + providerTurnOrdinal: 2, + nativeThreadHasTurns: true, + message, }); - const largePdf = Buffer.concat([ - pdfBytes.subarray(0, pdfBytes.length - 5), - Buffer.alloc( - (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length, - 32, - ), - Buffer.from("%%EOF"), - ]); - const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - yield* fileSystem.writeFile(documentPath, largePdf); + const sent = offeredMessages.at(-1)!.message.content; + assert.isArray(sent); + assert.lengthOf( + typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"), + budget === "partial-images" ? 1 : 0, + ); + assert.include(JSON.stringify(sent), JSON.stringify(imagePath).slice(1, -1)); yield* runtime.steerTurn({ threadId, runId: RunId.make("run-claude-attachments"), providerThread, - providerTurnId, - message: { - ...turnInput.message, - attachments: - budget === "same-message-images" - ? [document, attachment, attachment] - : [document], - }, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${laterAttemptId}`, + }), + message, }); - const sent = offeredMessages.at(-1)!.message.content; - assert.isArray(sent); + const steered = offeredMessages.at(-1)!.message.content; + assert.isArray(steered); assert.lengthOf( - typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"), + typeof steered === "string" ? [] : steered.filter((block) => block.type === "image"), 0, - budget, ); - assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1)); + assert.include(JSON.stringify(steered), JSON.stringify(imagePath).slice(1, -1)); + assert.isBelow( + Buffer.byteLength(JSON.stringify(offeredMessages.map((message) => message.message))), + 32_000_000, + ); return; } - if (!resumed) { - const undelivered = Buffer.from( - `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`, - ); - yield* fileSystem.writeFile( - path.join(attachmentsDir, attachmentRelativePath(document)!), - undelivered, - ); - failOpen = true; - assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit))); - assert.lengthOf(offeredMessages, 0); + if (budget === "retained-documents") { yield* fileSystem.writeFile( path.join(attachmentsDir, attachmentRelativePath(document)!), - pdfBytes, + Buffer.concat([ + pdfBytes.subarray(0, pdfBytes.length - 5), + Buffer.alloc(10 * 1024 * 1024, 32), + Buffer.from("%%EOF"), + ]), ); } - yield* runtime.startTurn(turnInput); - - const expectedImageBlock = { - type: "image", - source: { - type: "base64", - media_type: "image/png", - data: "AQIDBA==", - }, - } as const; - const expectedDocumentBlock = { - type: "document", - source: { - type: "base64", - media_type: "application/pdf", - data: Buffer.from(pdfBytes).toString("base64"), + yield* runtime.startTurn({ + ...turnInput, + message: { + ...turnInput.message, + text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt, + attachments: + budget === "retained-text" + ? [] + : budget === "retained-documents" + ? [document] + : [attachment, attachment], }, - } as const; - const expectedAttachmentPath = path.join( - attachmentsDir, - attachmentRelativePath(attachment)!, - ); - const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`; - const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes }; - const expectedContent = command - ? [ - requestBlock, - expectedImageBlock, - ...(!resumed ? [expectedDocumentBlock] : []), - { type: "text" as const, text: command + attachmentNotes }, - ] - : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock]; - assert.deepEqual(offeredMessages[0]?.message.content, expectedContent); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, }); + const largePdf = Buffer.concat([ + pdfBytes.subarray(0, pdfBytes.length - 5), + Buffer.alloc( + (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length, + 32, + ), + Buffer.from("%%EOF"), + ]); + const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); + yield* fileSystem.writeFile(documentPath, largePdf); yield* runtime.steerTurn({ threadId, runId: RunId.make("run-claude-attachments"), providerThread, providerTurnId, message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-claude-attachments-steer"), - text: prompt, - attachments: resumed ? [attachment] : [attachment, document], + ...turnInput.message, + attachments: + budget === "same-message-images" ? [document, attachment, attachment] : [document], }, }); + const sent = offeredMessages.at(-1)!.message.content; + assert.isArray(sent); + assert.lengthOf( + typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"), + 0, + budget, + ); + assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1)); + return; + } + if (!resumed) { + const undelivered = Buffer.from( + `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`, + ); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(document)!), + undelivered, + ); + failOpen = true; + assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit))); + assert.lengthOf(offeredMessages, 0); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(document)!), + pdfBytes, + ); + } + yield* runtime.startTurn(turnInput); - assert.equal(offeredMessages[1]?.priority, "now"); - assert.deepEqual(offeredMessages[1]?.message.content, expectedContent); - const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - for (const scenario of [ - "pages", - "bytes", - "invalid", - "invalid-page-tree", - "object-stream", - "encrypted", - "cyclic-tree", - "unterminated-string", - "missing-eof", - "escaped-name", - "incremental", - "indirect-count", - "indirect-type", - "indirect-kids", - "indirect-101-pages", - "aggregate-pages", - "retained-pages", - "delivery-failure", - "pasted-text", - "text-only", - ]) { - let attachments: ReadonlyArray = [document]; - if ( - ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario) - ) { - const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60; - const large = Buffer.from( - `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`, - ); - yield* fileSystem.writeFile(documentPath, large); - if (scenario === "aggregate-pages") { - const second = { - ...document, - id: ChatAttachmentId.make("second-pdf"), - name: "second.pdf", - }; - yield* fileSystem.copyFile( - documentPath, - path.join(attachmentsDir, attachmentRelativePath(second)!), - ); - attachments = [document, second]; - } - } else if (scenario.startsWith("indirect-")) { - const raw = - scenario === "indirect-count" || scenario === "indirect-101-pages" - ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF` - : scenario === "indirect-type" - ? pdfBytes - .toString() - .replace( - "%%EOF", - "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF", - ) - : pdfBytes - .toString() - .replace("/Kids [3 0 R]", "/Kids 4 0 R") - .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF"); - yield* fileSystem.writeFileString(documentPath, raw); - } else if (scenario === "bytes") { - yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1); - } else if (scenario === "invalid") { - yield* fileSystem.writeFileString(documentPath, "This is not a PDF"); - } else if (scenario === "invalid-page-tree") { - const malformedBytes = Buffer.from( - "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF", - ); - yield* fileSystem.writeFile(documentPath, malformedBytes); - } else if (["object-stream", "encrypted", "cyclic-tree"].includes(scenario)) { - const suffix = - scenario === "encrypted" - ? "/Encrypt 9 0 R" - : scenario === "cyclic-tree" - ? "/Count 0 /Kids [2 0 R]" - : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000"; - yield* fileSystem.writeFile( - documentPath, - Buffer.concat([ - pdfBytes.subarray(0, pdfBytes.length - 5), - Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`), - ]), - ); - } else if ( - ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes( - scenario, - ) - ) { - const raw = pdfBytes.toString(); - yield* fileSystem.writeFileString( + const expectedImageBlock = { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQIDBA==", + }, + } as const; + const expectedDocumentBlock = { + type: "document", + source: { + type: "base64", + media_type: "application/pdf", + data: Buffer.from(pdfBytes).toString("base64"), + }, + } as const; + const expectedAttachmentPath = path.join( + attachmentsDir, + attachmentRelativePath(attachment)!, + ); + const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); + const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`; + const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes }; + const expectedContent = command + ? [ + requestBlock, + expectedImageBlock, + ...(!resumed ? [expectedDocumentBlock] : []), + { type: "text" as const, text: command + attachmentNotes }, + ] + : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock]; + assert.deepEqual(offeredMessages[0]?.message.content, expectedContent); + + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + yield* runtime.steerTurn({ + threadId, + runId: RunId.make("run-claude-attachments"), + providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-claude-attachments-steer"), + text: prompt, + attachments: resumed ? [attachment] : [attachment, document], + }, + }); + + assert.equal(offeredMessages[1]?.priority, "now"); + assert.deepEqual(offeredMessages[1]?.message.content, expectedContent); + const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); + for (const scenario of [ + "pages", + "bytes", + "invalid", + "invalid-page-tree", + "object-stream", + "encrypted", + "cyclic-tree", + "unterminated-string", + "missing-eof", + "escaped-name", + "incremental", + "indirect-count", + "indirect-type", + "indirect-kids", + "indirect-101-pages", + "aggregate-pages", + "retained-pages", + "delivery-failure", + "pasted-text", + "text-only", + ]) { + let attachments: ReadonlyArray = [document]; + if ( + ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario) + ) { + const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60; + const large = Buffer.from( + `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`, + ); + yield* fileSystem.writeFile(documentPath, large); + if (scenario === "aggregate-pages") { + const second = { + ...document, + id: ChatAttachmentId.make("second-pdf"), + name: "second.pdf", + }; + yield* fileSystem.copyFile( documentPath, - scenario === "missing-eof" - ? raw.slice(0, -5) - : scenario === "escaped-name" - ? raw.replace("/Type /Page ", "/Type /Pa#67e ") - : raw.replace( - "%%EOF", - scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF", - ), + path.join(attachmentsDir, attachmentRelativePath(second)!), ); - } else if (scenario === "pasted-text") { - yield* fileSystem.writeFile(documentPath, pdfBytes); - attachments = [{ ...document, source: { _tag: "pasted-text" } }]; - } else { - attachments = []; - yield* fileSystem.remove(documentPath); - } - const steering = { - threadId, - runId: RunId.make("run-claude-attachments"), - providerThread, - providerTurnId, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make(`message-${scenario}`), - text: "Continue.", - attachments, - }, - } satisfies ProviderAdapter.ProviderAdapterV2SteerInput; - if (scenario === "delivery-failure") { - failOffer = true; - assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit))); + attachments = [document, second]; } - yield* runtime.steerTurn(steering); - - const sent = offeredMessages.at(-1)!.message.content; - const documents = - typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"); - assert.lengthOf( - documents, - ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0, - scenario, + } else if (scenario.startsWith("indirect-")) { + const raw = + scenario === "indirect-count" || scenario === "indirect-101-pages" + ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF` + : scenario === "indirect-type" + ? pdfBytes + .toString() + .replace( + "%%EOF", + "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF", + ) + : pdfBytes + .toString() + .replace("/Kids [3 0 R]", "/Kids 4 0 R") + .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF"); + yield* fileSystem.writeFileString(documentPath, raw); + } else if (scenario === "bytes") { + yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1); + } else if (scenario === "invalid") { + yield* fileSystem.writeFileString(documentPath, "This is not a PDF"); + } else if (scenario === "invalid-page-tree") { + const malformedBytes = Buffer.from( + "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF", + ); + yield* fileSystem.writeFile(documentPath, malformedBytes); + } else if (["object-stream", "encrypted", "cyclic-tree"].includes(scenario)) { + const suffix = + scenario === "encrypted" + ? "/Encrypt 9 0 R" + : scenario === "cyclic-tree" + ? "/Count 0 /Kids [2 0 R]" + : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000"; + yield* fileSystem.writeFile( + documentPath, + Buffer.concat([ + pdfBytes.subarray(0, pdfBytes.length - 5), + Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`), + ]), + ); + } else if ( + ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(scenario) + ) { + const raw = pdfBytes.toString(); + yield* fileSystem.writeFileString( + documentPath, + scenario === "missing-eof" + ? raw.slice(0, -5) + : scenario === "escaped-name" + ? raw.replace("/Type /Page ", "/Type /Pa#67e ") + : raw.replace( + "%%EOF", + scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF", + ), ); - if (scenario === "text-only") - assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue."); - else assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1)); + } else if (scenario === "pasted-text") { + yield* fileSystem.writeFile(documentPath, pdfBytes); + attachments = [{ ...document, source: { _tag: "pasted-text" } }]; + } else { + attachments = []; + yield* fileSystem.remove(documentPath); } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const steering = { + threadId, + runId: RunId.make("run-claude-attachments"), + providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`message-${scenario}`), + text: "Continue.", + attachments, + }, + } satisfies ProviderAdapter.ProviderAdapterV2SteerInput; + if (scenario === "delivery-failure") { + failOffer = true; + assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit))); + } + yield* runtime.steerTurn(steering); + + const sent = offeredMessages.at(-1)!.message.content; + const documents = + typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"); + assert.lengthOf( + documents, + ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0, + scenario, + ); + if (scenario === "text-only") + assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue."); + else assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1)); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -2649,238 +2617,236 @@ describe("ClaudeAdapterV2 attachments", () => { describe("ClaudeAdapterV2 native fork", () => { it.effect("forks a session from its original directory after the workspace root changes", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-fork-attachments-", - }); - const configDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-root-change-", - }); - const sourceSessionId = "11111111-1111-4111-8111-111111111111"; - const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002"; - const projectDir = NodePath.join(configDir, "projects", "-old-workspace"); - yield* fileSystem.makeDirectory(projectDir, { recursive: true }); - const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({ - type: parentUuid === null ? "user" : "assistant", - uuid, - parentUuid, - sessionId: sourceSessionId, - cwd: "/old-workspace", - isSidechain: false, - timestamp: "2026-10-01T00:00:00.000Z", - message, - }); - yield* fileSystem.writeFileString( - NodePath.join(projectDir, `${sourceSessionId}.jsonl`), - [ - entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }), - entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", { - role: "assistant", - content: [{ type: "text", text: "inherited answer" }], - }), - ] - .map((line) => JSON.stringify(line)) - .join("\n"), - ); - const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe( - Effect.provide( - ClaudeAdapterV2.layerQueryRunner.pipe( - Layer.provide(PortScanner.layerTest), - Layer.provide( - Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, { - native: undefined, - canonical: undefined, - }), - ), + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-fork-attachments-", + }); + const configDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-root-change-", + }); + const sourceSessionId = "11111111-1111-4111-8111-111111111111"; + const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002"; + const projectDir = NodePath.join(configDir, "projects", "-old-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({ + type: parentUuid === null ? "user" : "assistant", + uuid, + parentUuid, + sessionId: sourceSessionId, + cwd: "/old-workspace", + isSidechain: false, + timestamp: "2026-10-01T00:00:00.000Z", + message, + }); + yield* fileSystem.writeFileString( + NodePath.join(projectDir, `${sourceSessionId}.jsonl`), + [ + entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }), + entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", { + role: "assistant", + content: [{ type: "text", text: "inherited answer" }], + }), + ] + .map((line) => JSON.stringify(line)) + .join("\n"), + ); + const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe( + Effect.provide( + ClaudeAdapterV2.layerQueryRunner.pipe( + Layer.provide(PortScanner.layerTest), + Layer.provide( + Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, { + native: undefined, + canonical: undefined, + }), ), ), - ); - const openedQueries: Array = []; - const forkCalls: Array = []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: { CLAUDE_CONFIG_DIR: configDir }, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed(sourceSessionId), - open: (input) => - Effect.sync(() => { - openedQueries.push(input); - return { - messages: Stream.never, - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }; - }), - forkSession: (input) => - Effect.gen(function* () { - forkCalls.push(input); - return yield* realRunner.forkSession(input); - }), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const providerSessionId = ProviderSessionId.make("provider-session-claude-fork"); - const sourceThreadId = ThreadId.make("thread-claude-fork-source"); - const targetThreadId = ThreadId.make("thread-claude-fork-target"); - const runtime = yield* adapter.openSession({ - threadId: sourceThreadId, - providerSessionId, - modelSelection: { - instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), - model: "claude-sonnet-4-6", - }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - }), - }); - const sourceProviderThread = yield* runtime.ensureThread({ - threadId: sourceThreadId, - modelSelection: { - instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), - model: "claude-sonnet-4-6", - }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - }), - }); - const now = yield* DateTime.now; - const providerTurnId = ProviderTurnId.make("provider-turn-claude-source"); - const forkedProviderThread = yield* runtime.forkThread({ - sourceProviderThread, - sourceProviderTurns: [ - { - id: providerTurnId, - providerThreadId: sourceProviderThread.id, - nodeId: NodeId.make("node-claude-source"), - runAttemptId: RunAttemptId.make("run-attempt-claude-source"), - nativeTurnRef: { - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeId: sourceCursor, - strength: "weak", - }, - ordinal: 1, - status: "completed", - startedAt: now, - completedAt: now, - }, - ], - providerTurnId, - targetThreadId, - }); - - assert.deepEqual(forkCalls, [ + ), + ); + const openedQueries: Array = []; + const forkCalls: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: { CLAUDE_CONFIG_DIR: configDir }, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed(sourceSessionId), + open: (input) => + Effect.sync(() => { + openedQueries.push(input); + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: (input) => + Effect.gen(function* () { + forkCalls.push(input); + return yield* realRunner.forkSession(input); + }), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const providerSessionId = ProviderSessionId.make("provider-session-claude-fork"); + const sourceThreadId = ThreadId.make("thread-claude-fork-source"); + const targetThreadId = ThreadId.make("thread-claude-fork-target"); + const runtime = yield* adapter.openSession({ + threadId: sourceThreadId, + providerSessionId, + modelSelection: { + instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", + }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + }); + const sourceProviderThread = yield* runtime.ensureThread({ + threadId: sourceThreadId, + modelSelection: { + instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", + }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + }); + const now = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make("provider-turn-claude-source"); + const forkedProviderThread = yield* runtime.forkThread({ + sourceProviderThread, + sourceProviderTurns: [ { - sessionId: sourceSessionId, - options: { - upToMessageId: sourceCursor, + id: providerTurnId, + providerThreadId: sourceProviderThread.id, + nodeId: NodeId.make("node-claude-source"), + runAttemptId: RunAttemptId.make("run-attempt-claude-source"), + nativeTurnRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: sourceCursor, + strength: "weak", }, - environment: { CLAUDE_CONFIG_DIR: configDir }, - threadId: targetThreadId, - providerSessionId, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, }, - ]); - const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId; - assert.isString(forkedSessionId); - assert.notEqual(forkedSessionId, sourceSessionId); - const forkedTranscript = yield* fileSystem.readFileString( - NodePath.join(projectDir, `${forkedSessionId}.jsonl`), - ); - assert.include(forkedTranscript, "inherited answer"); - assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id); - assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId); - - yield* runtime.startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: targetThreadId, - projectId: ProjectId.make("project-claude-fork-target"), - title: "Claude fork target", - providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), - modelSelection: { - instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), - model: "claude-sonnet-4-6", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - activeProviderThreadId: forkedProviderThread.id, - lineage: { - parentThreadId: sourceThreadId, - relationshipToParent: "fork", - rootThreadId: sourceThreadId, - }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, + ], + providerTurnId, + targetThreadId, + }); + + assert.deepEqual(forkCalls, [ + { + sessionId: sourceSessionId, + options: { + upToMessageId: sourceCursor, }, + environment: { CLAUDE_CONFIG_DIR: configDir }, threadId: targetThreadId, - runId: RunId.make("run-claude-fork-target"), - runOrdinal: 1, - providerTurnOrdinal: 1, - attemptId: RunAttemptId.make("run-attempt-claude-fork-target"), - rootNodeId: NodeId.make("node-claude-fork-target-root"), - providerThread: forkedProviderThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-claude-fork-target"), - text: "Respond with fork ok", - attachments: [], - }, + providerSessionId, + }, + ]); + const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId; + assert.isString(forkedSessionId); + assert.notEqual(forkedSessionId, sourceSessionId); + const forkedTranscript = yield* fileSystem.readFileString( + NodePath.join(projectDir, `${forkedSessionId}.jsonl`), + ); + assert.include(forkedTranscript, "inherited answer"); + assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id); + assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId); + + yield* runtime.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: targetThreadId, + projectId: ProjectId.make("project-claude-fork-target"), + title: "Claude fork target", + providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), modelSelection: { instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), model: "claude-sonnet-4-6", }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - }), - }); + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: forkedProviderThread.id, + lineage: { + parentThreadId: sourceThreadId, + relationshipToParent: "fork", + rootThreadId: sourceThreadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId: targetThreadId, + runId: RunId.make("run-claude-fork-target"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("run-attempt-claude-fork-target"), + rootNodeId: NodeId.make("node-claude-fork-target-root"), + providerThread: forkedProviderThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-claude-fork-target"), + text: "Respond with fork ok", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", + }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + }); - assert.equal(openedQueries[0]?.options.resume, forkedSessionId); - assert.equal(openedQueries[0]?.options.sessionId, undefined); - assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace")); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + assert.equal(openedQueries[0]?.options.resume, forkedSessionId); + assert.equal(openedQueries[0]?.options.sessionId, undefined); + assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace")); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -5522,6 +5488,55 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #34393 a provider switch replayed a $skill from the handoff history + it.effect("dispatches only skills from the user's text, not from inline handoff history", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const homePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skill-handoff-" }); + const directory = path.join(homePath, "skills", "review"); + yield* fs.makeDirectory(directory, { recursive: true }); + yield* fs.writeFileString( + path.join(directory, "SKILL.md"), + "---\nname: review\n---\nFollow the review instructions.\n", + ); + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath }, + }); + const history = "Context handoff:\n[Historical user; user_message]\n$review the diff"; + const text = withInlineContext(history, "continue"); + yield* harness.runtime.startTurn({ + ...makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("skill-handoff"), + text, + attachments: [], + runtimePolicy: { ...CLAUDE_TEST_RUNTIME_POLICY, cwd: homePath }, + }), + inlineContextLength: text.length - "continue".length, + }); + + const content = harness.offeredMessages[0]?.message.content; + const blocks = + typeof content === "string" + ? [content] + : (content ?? []).map((block) => (block.type === "text" ? block.text : "")); + assert.isFalse(blocks.some((text) => text.startsWith("/review"))); + assert.include(blocks.join("\n"), "$review the diff"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #15475 MCP title arriving after the tool starts must survive to completion it.effect.each([ { isError: false, title: "Check weather" }, @@ -6515,136 +6530,80 @@ describe("ClaudeAdapterV2 background wake turns", () => { it.effect( "applies model, effort and Fast changes to a process running a background shell, but not thinking or a cleared effort", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const normal = { - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - model: "claude-opus-5-5", - } satisfies ModelSelection; - const turn = (ordinal: number, modelSelection: ModelSelection) => - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(`attempt-normal-background:${ordinal}`), - text: `Request ${ordinal}`, - attachments: [], - providerTurnOrdinal: ordinal, - modelSelection, - }); - const settle = Effect.gen(function* () { - yield* harness.offerAndWait(turnOneResult); - yield* Queue.take(harness.terminalReceipts); - }); - yield* harness.runtime.startTurn(turn(1, normal)); - const originalOptions = harness.getOpenedOptions(); - yield* harness.offerAndWait(wakeTaskStarted); - yield* settle; - assert.isTrue(yield* harness.hasPendingBackgroundWork); - - yield* harness.runtime.startTurn( - turn(2, { ...normal, options: [{ id: "fastMode", value: false }] }), - ); - yield* settle; - assert.deepEqual(harness.liveSelectionChanges, []); - - yield* harness.runtime.startTurn( - turn(3, { - ...normal, - options: [ - { id: "effort", value: "high" }, - { id: "ultracode", value: true }, - { id: "fastMode", value: true }, - ], - }), - ); - yield* settle; - yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" })); - yield* settle; - assert.deepEqual(harness.liveSelectionChanges, [ - { effortLevel: "high", fastMode: true, ultracode: true }, - { model: "claude-sonnet-4-6" }, - { effortLevel: "high", fastMode: null, ultracode: null }, - ]); - assert.strictEqual(harness.getOpenedOptions(), originalOptions); - assert.lengthOf(harness.offeredMessages, 4); - - for (const [ordinal, selection] of [ - [5, CLAUDE_TEST_RESTART_MODEL_SELECTION], - [6, { ...normal, model: "claude-haiku-4-5-20251001" }], - ] as const) { - const refused = yield* harness.runtime - .startTurn(turn(ordinal, selection)) - .pipe(Effect.result); - assert.equal(refused._tag, "Failure"); - if (refused._tag === "Failure") { - assert.instanceOf( - refused.failure.cause, - ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError, - ); - } - } - assert.strictEqual(harness.getOpenedOptions(), originalOptions); - assert.lengthOf(harness.offeredMessages, 4); - assert.lengthOf(harness.liveSelectionChanges, 3); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - // regression: #34549 a model change sent with a steer was shown but never applied to the turn. - it.effect("applies a model change sent with a steer to the running turn", () => - Effect.scoped( Effect.gen(function* () { const harness = yield* makeWakeHarness; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const opus = { + const now = yield* DateTime.now; + const normal = { instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, model: "claude-opus-5-5", } satisfies ModelSelection; - const input = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-steer-model-change"), - text: "Run the slow build.", - attachments: [], - modelSelection: opus, - }); - yield* harness.runtime.startTurn(input); - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${input.attemptId}`, - }), - modelSelection: { ...opus, model: "claude-sonnet-4-6" }, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("steer-model-change"), - text: "Which model are you?", + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-normal-background:${ordinal}`), + text: `Request ${ordinal}`, attachments: [], - }, + providerTurnOrdinal: ordinal, + modelSelection, + }); + const settle = Effect.gen(function* () { + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); }); + yield* harness.runtime.startTurn(turn(1, normal)); + const originalOptions = harness.getOpenedOptions(); + yield* harness.offerAndWait(wakeTaskStarted); + yield* settle; + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + yield* harness.runtime.startTurn( + turn(2, { ...normal, options: [{ id: "fastMode", value: false }] }), + ); + yield* settle; + assert.deepEqual(harness.liveSelectionChanges, []); + + yield* harness.runtime.startTurn( + turn(3, { + ...normal, + options: [ + { id: "effort", value: "high" }, + { id: "ultracode", value: true }, + { id: "fastMode", value: true }, + ], + }), + ); + yield* settle; + yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" })); + yield* settle; assert.deepEqual(harness.liveSelectionChanges, [ + { effortLevel: "high", fastMode: true, ultracode: true }, { model: "claude-sonnet-4-6" }, { effortLevel: "high", fastMode: null, ultracode: null }, ]); - assert.lengthOf(harness.offeredMessages, 2); + assert.strictEqual(harness.getOpenedOptions(), originalOptions); + assert.lengthOf(harness.offeredMessages, 4); + + for (const [ordinal, selection] of [ + [5, CLAUDE_TEST_RESTART_MODEL_SELECTION], + [6, { ...normal, model: "claude-haiku-4-5-20251001" }], + ] as const) { + const refused = yield* harness.runtime + .startTurn(turn(ordinal, selection)) + .pipe(Effect.result); + assert.equal(refused._tag, "Failure"); + if (refused._tag === "Failure") { + assert.instanceOf( + refused.failure.cause, + ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError, + ); + } + } + assert.strictEqual(harness.getOpenedOptions(), originalOptions); + assert.lengthOf(harness.offeredMessages, 4); + assert.lengthOf(harness.liveSelectionChanges, 3); + assert.isTrue(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -6655,126 +6614,174 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + // regression: #34549 a model change sent with a steer was shown but never applied to the turn. + it.effect("applies a model change sent with a steer to the running turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-steer-model-change"), + text: "Run the slow build.", + attachments: [], + modelSelection: opus, + }); + yield* harness.runtime.startTurn(input); + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }), + modelSelection: { ...opus, model: "claude-sonnet-4-6" }, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("steer-model-change"), + text: "Which model are you?", + attachments: [], + }, + }); + assert.deepEqual(harness.liveSelectionChanges, [ + { model: "claude-sonnet-4-6" }, + { effortLevel: "high", fastMode: null, ultracode: null }, + ]); + assert.lengthOf(harness.offeredMessages, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); it.effect("fails a model-changing steer when the turn ends during the selection change", () => - Effect.scoped( - Effect.gen(function* () { - let duringFlags: Effect.Effect = Effect.void; - const harness = yield* makeWakeHarnessWithOptions({ - applyFlagSettings: () => Effect.suspend(() => duringFlags), - }); - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const opus = { - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - model: "claude-opus-5-5", - } satisfies ModelSelection; - const input = makeClaudeTestTurnInput({ + Effect.gen(function* () { + let duringFlags: Effect.Effect = Effect.void; + const harness = yield* makeWakeHarnessWithOptions({ + applyFlagSettings: () => Effect.suspend(() => duringFlags), + }); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-steer-model-change-race"), + text: "Run the slow build.", + attachments: [], + modelSelection: opus, + }); + yield* harness.runtime.startTurn(input); + duringFlags = harness + .offerAndWait(turnOneResult) + .pipe(Effect.andThen(Queue.take(harness.terminalReceipts)), Effect.asVoid); + const steer = yield* harness.runtime + .steerTurn({ threadId: harness.threadId, + runId: input.runId, providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-steer-model-change-race"), - text: "Run the slow build.", - attachments: [], - modelSelection: opus, - }); - yield* harness.runtime.startTurn(input); - duringFlags = harness - .offerAndWait(turnOneResult) - .pipe(Effect.andThen(Queue.take(harness.terminalReceipts)), Effect.asVoid); - const steer = yield* harness.runtime - .steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${input.attemptId}`, - }), - modelSelection: { ...opus, model: "claude-sonnet-4-6" }, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("steer-model-change-race"), - text: "Which model are you?", - attachments: [], - }, - }) - .pipe(Effect.result); - assert.equal(steer._tag, "Failure"); - assert.lengthOf(harness.offeredMessages, 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }), + modelSelection: { ...opus, model: "claude-sonnet-4-6" }, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("steer-model-change-race"), + text: "Which model are you?", + attachments: [], + }, + }) + .pipe(Effect.result); + assert.equal(steer._tag, "Failure"); + assert.lengthOf(harness.offeredMessages, 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect("re-sends the model on the turn after a live selection change fails", () => - Effect.scoped( - Effect.gen(function* () { - let failFlags = true; - const harness = yield* makeWakeHarnessWithOptions({ - applyFlagSettings: () => - Effect.suspend(() => { - if (!failFlags) return Effect.void; - failFlags = false; - return Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "applyFlagSettings", - cause: new Error("control request failed"), - }), - ); - }), + Effect.gen(function* () { + let failFlags = true; + const harness = yield* makeWakeHarnessWithOptions({ + applyFlagSettings: () => + Effect.suspend(() => { + if (!failFlags) return Effect.void; + failFlags = false; + return Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "applyFlagSettings", + cause: new Error("control request failed"), + }), + ); + }), + }); + const now = yield* DateTime.now; + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-failed-live-change:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection, }); - const now = yield* DateTime.now; - const opus = { - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - model: "claude-opus-5-5", - } satisfies ModelSelection; - const turn = (ordinal: number, modelSelection: ModelSelection) => - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(`attempt-failed-live-change:${ordinal}`), - text: `Request ${ordinal}`, - attachments: [], - providerTurnOrdinal: ordinal, - modelSelection, - }); - yield* harness.runtime.startTurn(turn(1, opus)); - yield* harness.offerAndWait(turnOneResult); - yield* Queue.take(harness.terminalReceipts); - - const failed = yield* harness.runtime - .startTurn(turn(2, { ...opus, model: "claude-sonnet-4-6" })) - .pipe(Effect.result); - assert.equal(failed._tag, "Failure"); + yield* harness.runtime.startTurn(turn(1, opus)); + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); - // The process may now run Sonnet, so returning to Opus must send it. - yield* harness.runtime.startTurn(turn(3, opus)); - assert.deepEqual(harness.liveSelectionChanges, [ - { model: "claude-sonnet-4-6" }, - { effortLevel: "high", fastMode: null, ultracode: null }, - { model: "claude-opus-5-5" }, - { effortLevel: "medium", fastMode: false, ultracode: null }, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const failed = yield* harness.runtime + .startTurn(turn(2, { ...opus, model: "claude-sonnet-4-6" })) + .pipe(Effect.result); + assert.equal(failed._tag, "Failure"); + + // The process may now run Sonnet, so returning to Opus must send it. + yield* harness.runtime.startTurn(turn(3, opus)); + assert.deepEqual(harness.liveSelectionChanges, [ + { model: "claude-sonnet-4-6" }, + { effortLevel: "high", fastMode: null, ultracode: null }, + { model: "claude-opus-5-5" }, + { effortLevel: "medium", fastMode: false, ultracode: null }, + ]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -7000,86 +7007,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { it.effect.each(["cancelled", "interrupted", "denied", "permission_denied", undefined])( "preserves native tool non-execution metadata %s without inferring a denial from text", (kind) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-tool-non-execution"), - text: "Run the tool.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "user", - uuid: "tool-non-execution", - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: "tool-error", - is_error: true, - content: "STOP and wait for the user.", - }, - { type: "tool_result", tool_use_id: "tool-ok", is_error: false, content: "OK" }, - ], - }, - ...(kind === undefined - ? {} - : { - tool_result_meta: [ - { id: "tool-error", non_execution_kind: kind }, - { id: "tool-ok", non_execution_kind: null }, - ], - }), - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "result-non-execution", result: "Done" }), - ); - yield* Queue.take(harness.terminalReceipts); - const items = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" - ? [event.turnItem] - : [], - ); - const failed = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-error")!; - assert.equal( - failed.status, - kind === "cancelled" || kind === "interrupted" ? kind : "failed", - ); - assert.equal(failed.toolNonExecutionKind, kind); - const ok = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-ok")!; - assert.equal(ok.status, "completed"); - assert.equal(ok.toolNonExecutionKind, undefined); - const node = harness.events.findLast( - (event) => - event.type === "node.updated" && event.node.nativeItemRef?.nativeId === "tool-error", - ); - assert.equal(node?.type === "node.updated" ? node.node.status : undefined, failed.status); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("completes a turn after the resume dialog without a failed tool row", () => - Effect.scoped( Effect.gen(function* () { const harness = yield* makeWakeHarness; yield* harness.runtime.startTurn( @@ -7087,52 +7014,63 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-resume-dialog"), - text: "continue", + attemptId: RunAttemptId.make("attempt-tool-non-execution"), + text: "Run the tool.", attachments: [], }), ); - const dialog = yield* Effect.promise(() => - harness.getOpenedOptions()!.onUserDialog!( - { - dialogKind: "resume_return", - payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "user", + uuid: "tool-non-execution", + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "tool-error", + is_error: true, + content: "STOP and wait for the user.", + }, + { type: "tool_result", tool_use_id: "tool-ok", is_error: false, content: "OK" }, + ], }, - { signal: new AbortController().signal, requestId: "dialog-resume" }, - ), - ).pipe(Effect.forkScoped); - const request = yield* Queue.take(harness.runtimeRequestReceipts); - assert.deepEqual( - harness.events.flatMap((event) => - event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId - ? [event.node.parentNodeId] - : [], - ), - [NodeId.make("node-attempt-resume-dialog")], + ...(kind === undefined + ? {} + : { + tool_result_meta: [ + { id: "tool-error", non_execution_kind: kind }, + { id: "tool-ok", non_execution_kind: null }, + ], + }), + }), ); - yield* harness.runtime.respondToRuntimeRequest({ - requestId: request.runtimeRequest.id, - answers: { - [formatClaudeResumeCompactionQuestion({ ageMinutes: 90, estimatedTokens: 120000 })]: - "Keep full history", - }, - }); - assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "continue" }); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ uuid: "result-resume-dialog", result: "Done" }), + makeResultFrame({ uuid: "result-non-execution", result: "Done" }), ); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); - assert.deepEqual( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === "dialog-resume" - ? [event.turnItem.status] - : [], - ), - [], + yield* Queue.take(harness.terminalReceipts); + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? [event.turnItem] + : [], + ); + const failed = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-error")!; + assert.equal( + failed.status, + kind === "cancelled" || kind === "interrupted" ? kind : "failed", + ); + assert.equal(failed.toolNonExecutionKind, kind); + const ok = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-ok")!; + assert.equal(ok.status, "completed"); + assert.equal(ok.toolNonExecutionKind, undefined); + const node = harness.events.findLast( + (event) => + event.type === "node.updated" && event.node.nativeItemRef?.nativeId === "tool-error", ); + assert.equal(node?.type === "node.updated" ? node.node.status : undefined, failed.status); }).pipe( Effect.provide( Layer.mergeAll( @@ -7143,6 +7081,71 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("completes a turn after the resume dialog without a failed tool row", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-resume-dialog"), + text: "continue", + attachments: [], + }), + ); + const dialog = yield* Effect.promise(() => + harness.getOpenedOptions()!.onUserDialog!( + { + dialogKind: "resume_return", + payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, + }, + { signal: new AbortController().signal, requestId: "dialog-resume" }, + ), + ).pipe(Effect.forkScoped); + const request = yield* Queue.take(harness.runtimeRequestReceipts); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId + ? [event.node.parentNodeId] + : [], + ), + [NodeId.make("node-attempt-resume-dialog")], + ); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + answers: { + [formatClaudeResumeCompactionQuestion({ ageMinutes: 90, estimatedTokens: 120000 })]: + "Keep full history", + }, + }); + assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "continue" }); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "result-resume-dialog", result: "Done" }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "dialog-resume" + ? [event.turnItem.status] + : [], + ), + [], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); @@ -7155,136 +7158,131 @@ describe("ClaudeAdapterV2 background wake turns", () => { ].map((scenario) => ({ terminalReason, ...scenario })), ), )("handles $terminalReason (steered=$steered, exits=$queryExits)", (scenario) => - Effect.scoped( - Effect.gen(function* () { - const { terminalReason, steered, queryExits } = scenario; - const harness = yield* makeWakeHarness; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attemptId = RunAttemptId.make("attempt-steering-abort"); - const input = makeClaudeTestTurnInput({ + Effect.gen(function* () { + const { terminalReason, steered, queryExits } = scenario; + const harness = yield* makeWakeHarness; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attemptId = RunAttemptId.make("attempt-steering-abort"); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Audit the settings pages.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + if (steered) { + yield* harness.runtime.steerTurn({ threadId: harness.threadId, + runId: input.runId, providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId, - text: "Audit the settings pages.", - attachments: [], + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-steering-abort"), + text: "Include the hierarchy mock.", + attachments: [], + }, }); - yield* harness.runtime.startTurn(input); - if (steered) { - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }), - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("message-steering-abort"), - text: "Include the hierarchy mock.", - attachments: [], - }, - }); - assert.equal(harness.offeredMessages[1]?.priority, "now"); - } - const partialText = "The audit covers the `integ"; - if (!queryExits) - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000900", - text: partialText, - }), - ); - yield* harness.offerAndWait( + assert.equal(harness.offeredMessages[1]?.priority, "now"); + } + const partialText = "The audit covers the `integ"; + if (!queryExits) + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000900", + text: partialText, + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000901", + result: "", + terminalReason, + usage: { + input_tokens: 600, + output_tokens: 40, + cache_creation_input_tokens: 500, + cache_read_input_tokens: 2000, + }, + }), + ); + if (queryExits) { + yield* Queue.shutdown(harness.sdkMessages); + } else if (steered) { + yield* Queue.offer(harness.sdkMessages, wakeAssistant); + yield* Queue.offer( + harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000901", - result: "", - terminalReason, + uuid: "00000000-0000-4000-8000-000000000902", + result: "Audit finished after the steer.", usage: { - input_tokens: 600, - output_tokens: 40, - cache_creation_input_tokens: 500, - cache_read_input_tokens: 2000, + input_tokens: 3, + output_tokens: 6, + cache_creation_input_tokens: 2347, + cache_read_input_tokens: 9455, }, }), ); - if (queryExits) { - yield* Queue.shutdown(harness.sdkMessages); - } else if (steered) { - yield* Queue.offer(harness.sdkMessages, wakeAssistant); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000902", - result: "Audit finished after the steer.", - usage: { - input_tokens: 3, - output_tokens: 6, - cache_creation_input_tokens: 2347, - cache_read_input_tokens: 9455, - }, - }), - ); - } - const terminal = yield* Queue.take(harness.terminalReceipts); + } + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, queryExits ? "failed" : steered ? "completed" : "interrupted"); + if (steered && !queryExits && terminalReason === "aborted_streaming") { + // The steer cut this reply off mid-stream; it must not read as a finished answer. + const partial = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === partialText, + ); assert.equal( - terminal.status, - queryExits ? "failed" : steered ? "completed" : "interrupted", + partial?.type === "turn_item.updated" ? partial.turnItem.status : undefined, + "interrupted", ); - if (steered && !queryExits && terminalReason === "aborted_streaming") { - // The steer cut this reply off mid-stream; it must not read as a finished answer. - const partial = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text === partialText, - ); - assert.equal( - partial?.type === "turn_item.updated" ? partial.turnItem.status : undefined, - "interrupted", - ); - } - if (steered) { - if (!queryExits) - assert.isTrue( - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text === WAKE_ASSISTANT_TEXT, - ), - ); - const completed = harness.events.findLast( - (event) => event.type === "provider_turn.updated", - ); - assert.deepEqual( - completed?.type === "provider_turn.updated" - ? completed.providerTurn.turnTokenUsage - : undefined, - { - usageScope: "main_agent", - usageStatus: queryExits ? "partial" : "complete", - hasSubagents: false, - inputTokens: queryExits ? 3100 : 603 + 2847 + 11455, - outputTokens: queryExits ? 40 : 46, - cachedInputTokens: queryExits ? 2000 : 11455, - cacheCreationTokens: queryExits ? 500 : 2847, - ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }), - }, + } + if (steered) { + if (!queryExits) + assert.isTrue( + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === WAKE_ASSISTANT_TEXT, + ), ); - } - assert.lengthOf(harness.terminalEvents(), 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const completed = harness.events.findLast( + (event) => event.type === "provider_turn.updated", + ); + assert.deepEqual( + completed?.type === "provider_turn.updated" + ? completed.providerTurn.turnTokenUsage + : undefined, + { + usageScope: "main_agent", + usageStatus: queryExits ? "partial" : "complete", + hasSubagents: false, + inputTokens: queryExits ? 3100 : 603 + 2847 + 11455, + outputTokens: queryExits ? 40 : 46, + cachedInputTokens: queryExits ? 2000 : 11455, + cacheCreationTokens: queryExits ? 500 : 2847, + ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }), + }, + ); + } + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -10129,2125 +10127,514 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); it.effect("preserves typed Claude plans and todos through generic tool completion", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const assistantTools = ( - uuid: string, - tools: ReadonlyArray>, - parentToolUseId: string | null = null, - ) => - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: `msg_${uuid}`, - type: "message", - role: "assistant", - content: tools.map((tool) => ({ type: "tool_use", ...tool })), - stop_reason: "tool_use", - stop_sequence: null, - usage: { - input_tokens: 1, - output_tokens: 1, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - }, - }, - parent_tool_use_id: parentToolUseId, - uuid, - session_id: WAKE_NATIVE_SESSION, - }); - const toolResults = (uuid: string, toolUseIds: ReadonlyArray) => - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: toolUseIds.map((toolUseId) => ({ - type: "tool_result", - tool_use_id: toolUseId, - content: "ok", - })), - }, - parent_tool_use_id: null, - uuid, - session_id: WAKE_NATIVE_SESSION, - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-1"), - text: "Plan the work.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - assistantTools("00000000-0000-4000-8000-000000000501", [ - { - id: "tool-todo-1", - name: "TodoWrite", - input: { todos: [{ content: "Inspect", status: "in_progress" }] }, - }, - ]), - ); - yield* Queue.offer( - harness.sdkMessages, - assistantTools("00000000-0000-4000-8000-000000000501", [ - { - id: "tool-todo-1", - name: "TodoWrite", - input: { todos: [{ content: "Inspect", status: "in_progress" }] }, - }, - ]), - ); - yield* Queue.offer( - harness.sdkMessages, - toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, permissionMode: "bypassPermissions" }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "status", - status: null, - permissionMode: "plan", - uuid: "00000000-0000-4000-8000-000000000508", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTurnInit, - uuid: "00000000-0000-4000-8000-000000000509", - permissionMode: "plan", - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000503", - result: "Todo recorded.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-2"), - providerTurnOrdinal: 2, - text: "Finish the plan.", - attachments: [], - }), - ); - const canUseTool = harness.getOpenedOptions()?.canUseTool; - assert.isFunction(canUseTool); - const planMarkdown = "# Ready to implement\n\n1. Ship it."; - yield* Effect.promise(() => - canUseTool!( - "ExitPlanMode", - { plan: planMarkdown }, - { - signal: new AbortController().signal, - toolUseID: "tool-exit-plan-1", - requestId: "request-exit-plan-1", - }, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - assistantTools("00000000-0000-4000-8000-000000000504", [ - { - id: "tool-todo-2", - name: "TodoWrite", - input: { todos: [{ content: "Inspect", status: "completed" }] }, - }, - { id: "tool-exit-plan-1", name: "ExitPlanMode", input: { plan: planMarkdown } }, - ]), - ); - yield* Queue.offer( - harness.sdkMessages, - assistantTools( - "00000000-0000-4000-8000-000000000507", - [ - { - id: "tool-subagent-todo", - name: "TodoWrite", - input: { todos: [{ content: "Child-only work", status: "in_progress" }] }, - }, - ], - "tool-parent-agent", - ), - ); - yield* Queue.offer( - harness.sdkMessages, - toolResults("00000000-0000-4000-8000-000000000505", ["tool-todo-2", "tool-exit-plan-1"]), - ); - yield* Queue.offer( - harness.sdkMessages, - assistantTools("00000000-0000-4000-8000-000000000509", [ - { - id: "tool-todo-3", - name: "TodoWrite", - input: { todos: [{ content: "Implement", status: "pending" }] }, - }, - ]), - ); - yield* Queue.offer( - harness.sdkMessages, - toolResults("00000000-0000-4000-8000-000000000510", ["tool-todo-3"]), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000506", - result: "Plan captured.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - - const items = new Map( - harness.events.flatMap((event) => - event.type === "turn_item.updated" ? [[String(event.turnItem.id), event.turnItem]] : [], - ), - ); - const plans = new Map( - harness.events.flatMap((event) => - event.type === "plan.updated" ? [[String(event.plan.id), event.plan]] : [], - ), - ); - const todoItems = [...items.values()].filter((item) => item.type === "todo_list"); - const proposedItems = [...items.values()].filter((item) => item.type === "proposed_plan"); - assert.lengthOf(todoItems, 3); - assert.equal(todoItems[1]?.status, "completed"); - assert.deepEqual(todoItems[1]?.steps, [ - { id: "todo-0", text: "Inspect", status: "completed" }, - ]); - assert.deepEqual(todoItems[2]?.steps, [ - { id: "todo-0", text: "Implement", status: "pending" }, - ]); - assert.equal(todoItems[1]?.runId, todoItems[2]?.runId); - assert.lengthOf(proposedItems, 1); - assert.equal( - proposedItems[0]?.type === "proposed_plan" && proposedItems[0].markdown, - planMarkdown, - ); - assert.isTrue( - [...items.values()].some( - (item) => - item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-todo-2", - ), - ); - assert.isTrue( - [...items.values()].some( - (item) => - item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-exit-plan-1", - ), - ); - const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan"); - assert.equal(proposedPlan?.status, "active"); - assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]); - assert.deepEqual( - [...plans.values()] - .filter((plan) => plan.kind === "todo_list") - .map((plan) => plan.status), - ["superseded", "superseded", "active"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - type TaskToolCall = - | { name: "TaskCreate"; input: TaskCreateInput; output: TaskCreateOutput } - | { name: "TaskUpdate"; input: TaskUpdateInput; output: TaskUpdateOutput } - | { name: "TaskList"; input: Record; output: TaskListOutput }; - - function taskToolFrames( - tool: TaskToolCall, - nextUuid: () => string, - options?: { - parentToolUseId?: string; - isError?: boolean; - extraToolResult?: boolean; - nonExecutionKind?: string; - }, - ): ReadonlyArray { - const uuid = nextUuid(); - const toolUseId = `tool-${uuid}`; - const parentToolUseId = options?.parentToolUseId ?? null; - return [ - claudeSdkFrame({ - type: "assistant", - message: { - id: `msg_${uuid}`, - model: "claude-sonnet-4-6", - type: "message", - role: "assistant", - content: [{ type: "tool_use", id: toolUseId, name: tool.name, input: tool.input }], - stop_reason: "tool_use", - stop_sequence: null, - usage: { - input_tokens: 1, - output_tokens: 1, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - }, - }, - parent_tool_use_id: parentToolUseId, - uuid, - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: toolUseId, - content: - parentToolUseId !== null && tool.name === "TaskCreate" - ? `Task #${tool.output.task.id} created successfully: ${tool.output.task.subject}` - : parentToolUseId !== null && tool.name === "TaskUpdate" - ? tool.output.success - ? `Updated task #${tool.output.taskId} ${tool.output.updatedFields.join(", ")}` - : tool.output.error - : "Task tool finished.", - ...(options?.isError === undefined ? {} : { is_error: options.isError }), - }, - ...(options?.extraToolResult - ? [{ type: "tool_result", tool_use_id: "unrelated-tool", content: "ok" }] - : []), - ], - }, - // Like real Claude, subagent results carry only the text, no `tool_use_result`. - ...(parentToolUseId === null ? { tool_use_result: tool.output } : {}), - ...(options?.nonExecutionKind === undefined - ? {} - : { - tool_result_meta: [{ id: toolUseId, non_execution_kind: options.nonExecutionKind }], - }), - parent_tool_use_id: parentToolUseId, - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - ]; - } - - const makeTaskToolHarnessWithOptions = (environment: NodeJS.ProcessEnv = {}) => - Effect.gen(function* () { - const configDir = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped({ - prefix: "t3-claude-tasks-", - }); - const path = yield* Path.Path; - const harness = yield* makeWakeHarnessWithOptions({ - environment: { - CLAUDE_CONFIG_DIR: path.relative(CLAUDE_TEST_RUNTIME_POLICY.cwd ?? ".", configDir), - ...environment, - }, - }); - let sequence = 600; - let turn = 0; - const nextUuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; - const startTurn = Effect.fnUntraced(function* () { - turn++; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-claude-task-tools-${turn}`), - providerTurnOrdinal: turn, - text: "Update the task list.", - attachments: [], - }), - ); - }); - const call = Effect.fnUntraced(function* ( - tool: TaskToolCall, - options?: Parameters[2], - ) { - for (const frame of taskToolFrames(tool, nextUuid, options)) { - yield* harness.offerAndWait(frame); - } - }); - const finishTurn = Effect.fnUntraced(function* () { - yield* harness.offerAndWait( - makeResultFrame({ uuid: nextUuid(), result: "Task list updated." }), - ); - return yield* Queue.take(harness.terminalReceipts); - }); - const plans = () => - harness.events.flatMap((event) => - event.type === "plan.updated" && event.plan.kind === "todo_list" ? [event.plan] : [], - ); - // Registers a running subagent so frames carrying its tool_use_id as - // parent_tool_use_id are processed instead of held for an unknown owner. - const launchSubagent = (toolUseId: string) => - harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: `task-${toolUseId}`, - tool_use_id: toolUseId, - description: "Work on tasks", - task_type: "local_agent", - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - ); - return { configDir, startTurn, call, launchSubagent, finishTurn, plans }; - }); - - const makeTaskToolHarness = makeTaskToolHarnessWithOptions(); - - const createTask = (id: string, subject: string): TaskToolCall => ({ - name: "TaskCreate", - input: { subject: `Requested ${subject}`, description: `Work on ${subject}.` }, - output: { task: { id, subject } }, - }); - const updateTask = (input: TaskUpdateInput, success = true): TaskToolCall => ({ - name: "TaskUpdate", - input, - output: { success, taskId: input.taskId, updatedFields: ["status"] }, - }); - - it.effect("persists a todo_list from inline Claude task-tool frames", () => - Effect.gen(function* () { - let sequence = 700; - const nextUuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; - const prompt = "Track a synthetic task."; - const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript({ - provider: "claudeAgent", - protocol: "claude-agent-sdk.query", - version: "1", - scenario: "claude_task_tools_inline", - metadata: { nativeSessionId: WAKE_NATIVE_SESSION }, - entries: [ - { - type: "expect_outbound", - frame: { - type: "query.open", - options: { - model: "claude-sonnet-4-6", - tools: { type: "preset", preset: "claude_code" }, - permissionMode: "bypassPermissions", - allowDangerouslySkipPermissions: true, - settings: { showThinkingSummaries: true }, - sessionId: WAKE_NATIVE_SESSION, - }, - }, - }, - { - type: "expect_outbound", - frame: { - type: "prompt.offer", - message: { - type: "user", - message: { role: "user", content: prompt }, - parent_tool_use_id: null, - }, - }, - }, - ...[ - ...taskToolFrames(createTask("1", "Inspect"), nextUuid), - ...taskToolFrames(updateTask({ taskId: "1", status: "in_progress" }), nextUuid), - makeResultFrame({ uuid: nextUuid(), result: "Task recorded." }), - ].map((frame) => ({ type: "emit_inbound" as const, frame })), - ], - } satisfies ProviderReplayTranscript); - const materialized = yield* materializeFixtureInput({ - scenario: transcript.scenario, - fixtureInput: { steps: [{ type: "message", text: prompt }] }, - driver: ProviderDriverKind.make("claudeAgent"), - modelSelection: CLAUDE_MODEL_SELECTION, - }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime); - const scenario = { name: transcript.scenario, transcript, ...materialized }; - yield* Effect.gen(function* () { - const result = yield* runOrchestratorV2Scenario(scenario); - assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); - const projection = projectionFor(result, transcript.scenario); - assertSemanticProjectionIntegrity(projection); - const plans = projection.plans.filter((plan) => plan.kind === "todo_list"); - assert.lengthOf(plans, 1); - assert.deepEqual( - plans[0]?.steps.map(({ id, text, status }) => ({ id, text, status })), - [{ id: "task-1", text: "Inspect", status: "running" }], - ); - assert.lengthOf( - projection.turnItems.filter((item) => item.type === "todo_list"), - 1, - ); - }).pipe( - Effect.provide(layerProviderReplay(scenario, ClaudeOrchestratorReplayHarness)), - provideDeterministicTestRuntime, - Effect.scoped, - ); - }), - ); - - it.effect( - "projects TaskCreate and TaskUpdate into one plan per turn and supersedes it later", - () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Inspect")); - yield* harness.call(createTask("2", "Implement")); - yield* harness.call(updateTask({ taskId: "1", status: "in_progress" })); - yield* harness.finishTurn(); - - const firstTurnPlans = harness.plans(); - assert.lengthOf(firstTurnPlans, 3); - assert.equal(new Set(firstTurnPlans.map((plan) => plan.id)).size, 1); - assert.deepEqual(firstTurnPlans.at(-1)?.steps, [ - { id: "task-1", text: "Inspect", status: "running" }, - { id: "task-2", text: "Implement", status: "pending" }, - ]); - const firstPlan = firstTurnPlans.at(-1)!; - - yield* harness.startTurn(); - yield* harness.call(updateTask({ taskId: "1", status: "completed", subject: "Inspected" })); - yield* harness.finishTurn(); - - const laterPlans = harness.plans().slice(firstTurnPlans.length); - assert.lengthOf(laterPlans, 2); - assert.equal(laterPlans[0]?.id, firstPlan.id); - assert.equal(laterPlans[0]?.status, "superseded"); - const newPlan = laterPlans[1]!; - assert.notEqual(newPlan.id, firstPlan.id); - assert.notEqual(newPlan.runId, firstPlan.runId); - assert.deepEqual(newPlan.steps, [ - { id: "task-1", text: "Inspected", status: "completed" }, - { id: "task-2", text: "Implement", status: "pending" }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect("removes deleted tasks without resurrecting them on later updates or turns", () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Discard")); - yield* harness.call(createTask("2", "Keep")); - yield* harness.call(updateTask({ taskId: "1", status: "deleted" })); - yield* harness.call(updateTask({ taskId: "1", status: "pending" })); - yield* harness.finishTurn(); - assert.lengthOf(harness.plans(), 3); - assert.deepEqual(harness.plans().at(-1)?.steps, [ - { id: "task-2", text: "Keep", status: "pending" }, - ]); - - yield* harness.startTurn(); - yield* harness.call(updateTask({ taskId: "2", status: "in_progress" })); - yield* harness.finishTurn(); - assert.deepEqual(harness.plans().at(-1)?.steps, [ - { id: "task-2", text: "Keep", status: "running" }, - ]); - for (const plan of harness.plans().slice(2)) { - assert.isFalse(plan.steps.some((step) => step.id === "task-1")); - } - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect.each([ - { - tool: updateTask({ taskId: "2", status: "completed" }), - listId: undefined, - directory: WAKE_NATIVE_SESSION, - status: "completed", - }, - { - tool: createTask("2", "Implement"), - listId: " list/ID ", - directory: "list-ID", - status: "pending", - }, - ] as const)( - "recovers persisted tasks on the first $tool.name after restart", - ({ tool, listId, directory, status }) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const harness = yield* makeTaskToolHarnessWithOptions({ CLAUDE_CODE_TASK_LIST_ID: listId }); - const tasksDir = `${harness.configDir}/tasks/${directory}`; - yield* fs.makeDirectory(tasksDir, { recursive: true }); - // The native tool has already written its result before emitting the SDK frame. - for (const task of [ - { id: "1", subject: "Inspect", status: "completed" }, - { id: "2", subject: "Implement", status }, - { id: "3", subject: "Internal", status: "pending", metadata: { _internal: true } }, - ]) { - yield* fs.writeFileString( - `${tasksDir}/${task.id}.json`, - JSON.stringify({ description: "", blocks: [], blockedBy: [], ...task }), - ); - } - yield* fs.writeFileString(`${tasksDir}/4.json`, "{"); - yield* fs.makeDirectory(`${tasksDir}/5.json`); - - yield* harness.startTurn(); - yield* harness.call(tool); - assert.equal((yield* harness.finishTurn()).status, "completed"); - assert.deepEqual( - harness.plans().map((plan) => plan.steps), - [ - [ - { id: "task-1", text: "Inspect", status: "completed" }, - { id: "task-2", text: "Implement", status }, - ], - ], - ); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect( - "publishes an empty task list when the first TaskUpdate after restart deletes the last task", - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const harness = yield* makeTaskToolHarness; - const tasksDir = `${harness.configDir}/tasks/${WAKE_NATIVE_SESSION}`; - // Claude has removed the task file before emitting the SDK frame. - yield* fs.makeDirectory(tasksDir, { recursive: true }); - yield* fs.writeFileString(`${tasksDir}/.highwatermark`, "1"); - - yield* harness.startTurn(); - yield* harness.call(updateTask({ taskId: "1", status: "deleted" })); - assert.equal((yield* harness.finishTurn()).status, "completed"); - assert.deepEqual( - harness.plans().map((plan) => plan.steps), - [[]], - ); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect("replaces task state with TaskList, including an empty list", () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Stale")); - yield* harness.call({ - name: "TaskList", - input: {}, - output: { - tasks: [ - { id: "2", subject: "Queued", status: "pending", blockedBy: [] }, - { id: "3", subject: "Working", status: "in_progress", blockedBy: [] }, - { id: "4", subject: "Done", status: "completed", blockedBy: [] }, - ], - }, - }); - yield* harness.call(updateTask({ taskId: "1", status: "in_progress" })); - yield* harness.call(updateTask({ taskId: "2", status: "in_progress" })); - yield* harness.call({ name: "TaskList", input: {}, output: { tasks: [] } }); - yield* harness.call(updateTask({ taskId: "2", status: "pending" })); - yield* harness.finishTurn(); - const plans = harness.plans(); - assert.lengthOf(plans, 4); - assert.deepEqual(plans[1]?.steps, [ - { id: "task-2", text: "Queued", status: "pending" }, - { id: "task-3", text: "Working", status: "running" }, - { id: "task-4", text: "Done", status: "completed" }, - ]); - assert.deepEqual(plans[2]?.steps, [ - { id: "task-2", text: "Queued", status: "running" }, - { id: "task-3", text: "Working", status: "running" }, - { id: "task-4", text: "Done", status: "completed" }, - ]); - assert.deepEqual(plans[3]?.steps, []); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect("applies subagent task tools to the parent turn's shared task list", () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Main task")); - yield* harness.launchSubagent("tool-parent-agent"); - const child = { parentToolUseId: "tool-parent-agent" }; - yield* harness.call(updateTask({ taskId: "1", status: "completed" }), child); - yield* harness.call(createTask("2", "Child task"), child); - yield* harness.call( - { - name: "TaskUpdate", - input: { taskId: "2", status: "completed" }, - output: { - success: false, - taskId: "2", - updatedFields: [], - error: "Tests must pass before completing.", - }, - }, - child, - ); - yield* harness.call(updateTask({ taskId: "2", status: "in_progress" }), { - ...child, - isError: true, - }); - // A cancelled call never ran, even without `is_error`. - yield* harness.call(updateTask({ taskId: "2", status: "completed" }), { - ...child, - nonExecutionKind: "cancelled", - }); - yield* harness.finishTurn(); - const plans = harness.plans(); - assert.lengthOf(plans, 3); - assert.equal(new Set(plans.map((plan) => plan.id)).size, 1); - assert.deepEqual(plans.at(-1)?.steps, [ - { id: "task-1", text: "Main task", status: "completed" }, - { id: "task-2", text: "Child task", status: "pending" }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect("recovers persisted tasks when a subagent's TaskList comes first", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const harness = yield* makeTaskToolHarness; - const tasksDir = `${harness.configDir}/tasks/${WAKE_NATIVE_SESSION}`; - yield* fs.makeDirectory(tasksDir, { recursive: true }); - yield* fs.writeFileString( - `${tasksDir}/1.json`, - JSON.stringify({ id: "1", subject: "Inspect", status: "pending", blockedBy: [] }), - ); - - yield* harness.startTurn(); - yield* harness.launchSubagent("tool-parent-agent"); - yield* harness.call( - { name: "TaskList", input: {}, output: { tasks: [] } }, - { parentToolUseId: "tool-parent-agent" }, - ); - yield* harness.call(updateTask({ taskId: "1", status: "completed" })); - yield* harness.finishTurn(); - assert.deepEqual(harness.plans().at(-1)?.steps, [ - { id: "task-1", text: "Inspect", status: "completed" }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - // regression: #14964 structured task output attaches to exactly one tool result - it.effect("does not associate structured task output with multiple tool results", () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Ambiguous"), { extraToolResult: true }); - yield* harness.finishTurn(); - assert.deepEqual(harness.plans(), []); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - it.effect("resolves API retries on resumed assistant activity", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-api-retry"), - text: "Open github.com.", - attachments: [], - }), - ); - - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "api_retry", - attempt: 2, - max_retries: 10, - retry_delay_ms: 1_500, - error_status: 529, - error: "overloaded", - uuid: "00000000-0000-4000-8000-000000000201", - session_id: WAKE_NATIVE_SESSION, - }), - ); - const retryItems = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.retry !== undefined - ? [event.turnItem] - : [], - ); - yield* harness.until(() => retryItems().length === 1); - const runningRetry = retryItems()[0]; - assert.equal(runningRetry?.status, "running"); - assert.equal(runningRetry?.failure.code, "api_error_529"); - assert.deepEqual(runningRetry?.retry, { - attempt: 2, - maxAttempts: 10, - retryDelayMs: 1_500, - }); - - // The stream starting again settles the retry before any assistant message completes. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "stream_event", - event: { type: "message_start", message: { id: "api-retry-recovered-message" } }, - parent_tool_use_id: null, - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000000204", - }), - ); - yield* harness.until(() => retryItems().length === 2); - assert.lengthOf(harness.terminalEvents(), 0); - const recoveredRetry = retryItems()[1]; - assert.equal(recoveredRetry?.id, runningRetry?.id); - assert.equal(recoveredRetry?.status, "completed"); - assert.equal(recoveredRetry?.title, "Provider recovered"); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000202", - text: "Opening GitHub.", - }), - ); - - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000203", - result: "Opened GitHub.", - }), - ); - yield* harness.awaitTerminal(1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect.each(["api_error", "overloaded_status"] as const)( - "fails a success-shaped Claude result with %s", - (terminalReason) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-structured-terminal-failure"), - text: "Complete the task.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000205", - result: "Provider failure details.", - isError: false, - ...(terminalReason === "overloaded_status" - ? { apiErrorStatus: 529 } - : { terminalReason }), - }), - ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.isNotEmpty(terminal.failure.message); - assert.equal(terminal.failure.class, "provider_error"); - assert.isFalse( - harness.events.some( - (event) => - event.type === "message.updated" && - event.message.text === "Provider failure details.", - ), - ); - assert.equal( - terminal.failure.code, - terminalReason === "overloaded_status" ? "api_error_529" : terminalReason, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - // Context exhaustion reports blocking_limit even when the rate-limit window is allowed. - it.effect.each([ - { - windowStatus: "allowed", - expectedClass: "provider_error", - expectedMessage: "Claude stopped: the prompt exceeds the model's context window.", - }, - { - windowStatus: "rejected", - expectedClass: "usage_limit", - expectedMessage: "Claude usage limit reached. Send the message again once the limit resets.", - }, - ] as const)( - "classifies blocking_limit by its rate-limit evidence ($windowStatus window)", - ({ windowStatus, expectedClass, expectedMessage }) => - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-blocking-limit-${windowStatus}`), - text: "Continue.", - attachments: [], - }), - ); - yield* Queue.offerAll(harness.sdkMessages, [ - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { status: windowStatus, rateLimitType: "five_hour" }, - uuid: "00000000-0000-4000-8000-000000000660", - session_id: WAKE_NATIVE_SESSION, - }), - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000661", - error: "invalid_request", - text: "Prompt is too long", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000662", - result: "Prompt is too long", - isError: true, - numTurns: 189, - terminalReason: "blocking_limit", - }), - ]); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.equal(terminal.failure.class, expectedClass); - assert.include(terminal.failure.message, expectedMessage); - assert.equal(terminal.failure.code, "blocking_limit"); - if (expectedClass === "provider_error") { - assert.include(terminal.failure.message, "/compact"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - - const providerThreadRosterEvents = ( - events: ReadonlyArray, - ) => - events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_thread.updated" } - > => event.type === "provider_thread.updated", - ); - - it.effect( - "uses task_started as an incremental roster fallback, keeps its tool call, and clears internal work on empty snapshot", - () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const emptyRoster = claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [], - uuid: "00000000-0000-4000-8000-000000000202", - session_id: WAKE_NATIVE_SESSION, - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-roster-fallback"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_background_command", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: WAKE_TOOL_USE_ID, - name: "Bash", - input: { - command: "python3 audit.py > audit.log 2>&1", - run_in_background: true, - }, - }, - ], - }, - parent_tool_use_id: null, - uuid: "background-command-launch", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - - const afterStart = providerThreadRosterEvents(harness.events).filter( - (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, - ); - assert.isAtLeast(afterStart.length, 1); - const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]; - assert.equal(started?.taskId, WAKE_TASK_ID); - assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID); - - const command = harness.events.find( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === WAKE_TOOL_USE_ID, - ); - assert.equal(command?.type, "turn_item.updated"); - if (command?.type !== "turn_item.updated") return; - const details = { - command: "python3 audit.py > audit.log 2>&1", - itemId: command.turnItem.id, - }; - assert.deepInclude( - afterStart.at(-1)?.providerThread.pendingBackgroundTasks?.[0], - details, - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [{ task_id: WAKE_TASK_ID, task_type: "local_bash", description: "Audit" }], - uuid: "background-command-snapshot", - session_id: WAKE_NATIVE_SESSION, - }), - ); - assert.deepInclude( - providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks?.[0], - details, - ); - - // A foreground command that later moves to the background keeps its tool call too. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: "moved-shell", - tool_use_id: "toolu_moved_shell", - description: "Foreground build", - is_backgrounded: false, - task_type: "local_bash", - uuid: "00000000-0000-4000-8000-000000000204", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [ - { - task_id: "subagent-shell", - task_type: "local_bash", - description: "sleep 150", - parent_task_id: "agent-1", - }, - { - task_id: WAKE_TASK_ID, - task_type: "local_bash", - description: WAKE_TASK_DESCRIPTION, - }, - { - task_id: "moved-shell", - task_type: "local_bash", - description: "Foreground build", - }, - ], - uuid: "00000000-0000-4000-8000-000000000203", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.until(() => - providerThreadRosterEvents(harness.events).some( - (event) => - event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1" && - event.providerThread.pendingBackgroundTasks[1]?.nativeItemId === WAKE_TOOL_USE_ID && - event.providerThread.pendingBackgroundTasks[2]?.nativeItemId === - "toolu_moved_shell", - ), - ); - - yield* harness.offerAndWait(emptyRoster); - assert.include( - ( - providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks ?? [] - ).map((task) => task.taskId), - WAKE_TASK_ID, - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("holds only the background tasks the agent marks awaited, until they end", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; - if (awaitBackgroundTasks === undefined) { - throw new Error("Claude adapter runtime must expose awaitBackgroundTasks."); - } - const roster = (tasks: ReadonlyArray, uuid: string) => - claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: tasks.map((taskId) => ({ - task_id: taskId, - task_type: "local_bash", - description: taskId, - })), - uuid, - session_id: WAKE_NATIVE_SESSION, - }); - const nextRoster = Effect.fn("nextRoster")(function* ( - matches: (tasks: ReadonlyArray) => boolean, - ) { - while (true) { - const { providerThread } = yield* Queue.take(harness.providerThreadReceipts); - const tasks = providerThread.pendingBackgroundTasks ?? []; - if (matches(tasks)) return tasks; - } - }); - const marks = (tasks: ReadonlyArray) => - tasks.map((task) => [task.taskId, task.awaited === true]); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-awaited-roster"), - text: "Run the tests in the background and the dev server.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - roster([WAKE_TASK_ID, "dev-server"], "00000000-0000-4000-8000-000000000301"), - ); - yield* nextRoster((tasks) => tasks.length === 2); - - const marked = yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: [WAKE_TASK_ID, "already-finished"], - awaited: true, - }); - assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]); - assert.deepStrictEqual( - marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))), - [ - [WAKE_TASK_ID, true], - ["dev-server", false], - ], - ); - // A replacing level rebuilds every entry; the mark must survive it. - yield* Queue.offer( - harness.sdkMessages, - roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000302"), - ); - assert.deepStrictEqual( - marks(yield* nextRoster((tasks) => tasks[0]?.taskId === "dev-server")), - [ - ["dev-server", false], - [WAKE_TASK_ID, true], - ], - ); - - // Once the task ends, a reused id starts unmarked. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ ...wakeNotification, uuid: "00000000-0000-4000-8000-000000000303" }), - ); - yield* nextRoster((tasks) => tasks.length === 1); - yield* Queue.offer( - harness.sdkMessages, - roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"), - ); - assert.deepStrictEqual(marks(yield* nextRoster((tasks) => tasks.length === 2)), [ - ["dev-server", false], - [WAKE_TASK_ID, false], - ]); - - yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: ["dev-server"], - awaited: true, - }); - assert.deepStrictEqual( - marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))), - [ - ["dev-server", true], - [WAKE_TASK_ID, false], - ], - ); - const released = yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: ["dev-server"], - awaited: false, - }); - assert.deepStrictEqual(released.matched, ["dev-server"]); - assert.deepStrictEqual( - marks(yield* nextRoster((tasks) => !tasks.some((task) => task.awaited === true))), - [ - ["dev-server", false], - [WAKE_TASK_ID, false], - ], - ); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* Queue.take(harness.terminalReceipts); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("keeps a running Claude monitor typed after many newer monitors end", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - let frameNumber = 0; - const nextUuid = () => `00000000-0000-4000-8000-${String(++frameNumber).padStart(12, "0")}`; - const monitorFrames = (index: number) => { - const taskId = `monitor-task-${index}`; - const toolUseId = `toolu_monitor_${index}`; - const description = `Monitor ${index}`; - return { - taskId, - start: [ - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: `msg_monitor_${index}`, - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: toolUseId, - name: "Monitor", - input: { description, command: "sleep 8 && echo MONITOR_DONE" }, - }, - ], - stop_reason: null, - stop_sequence: null, - usage: { input_tokens: 1, output_tokens: 1 }, - }, - parent_tool_use_id: null, - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: taskId, - tool_use_id: toolUseId, - description, - is_backgrounded: true, - task_type: "local_bash", - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: toolUseId, - content: `Monitor started (task ${taskId}).`, - }, - ], - }, - parent_tool_use_id: null, - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - tool_use_result: { taskId, persistent: false }, - }), - ], - end: claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: taskId, - tool_use_id: toolUseId, - status: "completed", - output_file: `/tmp/claude-replay/tasks/${taskId}.output`, - summary: `Monitor "${description}" stream ended`, - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - }; - }; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-many-monitors"), - text: "Watch the deploy, then re-arm short watches.", - attachments: [], - }), - ); - const longRunning = monitorFrames(0); - for (const frame of longRunning.start) { - yield* Queue.offer(harness.sdkMessages, frame); - } - for (let index = 1; index <= 65; index++) { - const monitor = monitorFrames(index); - for (const frame of monitor.start) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.offer(harness.sdkMessages, monitor.end); - } - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [ - { - task_id: longRunning.taskId, - task_type: "local_bash", - description: "Monitor 0", - }, - ], - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: nextUuid(), result: "Watching." }), - ); - yield* harness.awaitTerminal(1); - - const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks; - assert.deepEqual(roster, [ - { - taskId: longRunning.taskId, - kind: "monitor", - description: "Monitor 0", - nativeItemId: "toolu_monitor_0", - }, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - const scheduleWakeupFrames = (input: { - readonly toolUseId: string; - readonly uuids: readonly [string, string]; - readonly toolInput: Record; - readonly scheduledFor: number; - }) => [ - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: `msg_${input.toolUseId}`, - type: "message", - role: "assistant", - content: [ - { type: "tool_use", id: input.toolUseId, name: "ScheduleWakeup", input: input.toolInput }, - ], - stop_reason: null, - stop_sequence: null, - usage: { input_tokens: 1, output_tokens: 1 }, - }, - parent_tool_use_id: null, - uuid: input.uuids[0], - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [{ type: "tool_result", tool_use_id: input.toolUseId, content: "Scheduled." }], - }, - parent_tool_use_id: null, - uuid: input.uuids[1], - session_id: WAKE_NATIVE_SESSION, - tool_use_result: { - scheduledFor: input.scheduledFor, - clampedDelaySeconds: 60, - wasClamped: false, - }, - }), - ]; - - const startScheduleWakeupTurn = Effect.fnUntraced(function* ( - harness: Effect.Success, - result = makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002103", - result: "Scheduled.", - }), - ) { - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-1"), - text: "Wake up in a minute.", - attachments: [], - }), - ); - for (const frame of scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_1", - uuids: ["00000000-0000-4000-8000-000000002101", "00000000-0000-4000-8000-000000002102"], - toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false }, - scheduledFor: DateTime.toEpochMillis(now) + 60_000, - })) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.offer(harness.sdkMessages, result); - yield* harness.awaitTerminal(1); - }); - - const publishedRoster = (harness: Effect.Success) => - providerThreadRosterEvents(harness.events).at(-1)?.providerThread.pendingBackgroundTasks ?? []; - - it.effect.each([ - { rescheduled: false, firedAfter: "60 seconds" }, - { rescheduled: true, firedAfter: "60 seconds" }, - // Claude fires one-shot wakeups early, so the wake init can precede scheduledFor. - { rescheduled: false, firedAfter: "30 seconds" }, - ] as const)( - "a fired ScheduleWakeup holds completion only while its wake turn reschedules (rescheduled=$rescheduled, fired after $firedAfter)", - ({ rescheduled, firedAfter }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* startScheduleWakeupTurn(harness); - assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); - assert.isTrue( - yield* harness.hasPendingBackgroundWork, - "a wakeup past the idle timeout must keep the session from being released", - ); - - yield* TestClock.adjust(firedAfter); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.awaitContinuation(1); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-2"), - text: "say WOKE", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - if (rescheduled) { - for (const frame of scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_2", - uuids: [ - "00000000-0000-4000-8000-000000002201", - "00000000-0000-4000-8000-000000002202", - ], - toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "loop", noop: false }, - scheduledFor: DateTime.toEpochMillis(now) + 60_000, - })) { - yield* harness.offerAndWait(frame); - } - } - yield* harness.offerAndWait( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002203", text: "WOKE" }), - ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002204", result: "WOKE" }), - ); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.equal(backgroundWorkHoldsCompletion(publishedRoster(harness)), rescheduled); - assert.equal(yield* harness.hasPendingBackgroundWork, rescheduled); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("a user turn before the wakeup fires keeps the pending wakeup's hold", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* startScheduleWakeupTurn(harness); - yield* TestClock.adjust("10 seconds"); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-user"), - text: "What time is it?", - attachments: [], - providerTurnOrdinal: 2, - }), - ); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002401", text: "Noon." }), - ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002402", result: "Noon." }), - ); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("a task notification waking Claude just before the wakeup keeps its hold", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task"), - text: "Run the build in the background and check back in two minutes.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - for (const frame of scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_fallback", - uuids: ["00000000-0000-4000-8000-000000002501", "00000000-0000-4000-8000-000000002502"], - toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" }, - scheduledFor: DateTime.toEpochMillis(now) + 120_000, - })) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - - yield* TestClock.adjust("60 seconds"); - // Claude runs an empty turn for the notification and opens the real one right after, - // both before the wake run attaches. - yield* harness.offerAndWait(wakeNotification); - yield* Queue.offer(harness.sdkMessages, wakeTurnInit); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002503", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000002504" }), - ); - yield* harness.awaitContinuation(1); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.isTrue( - backgroundWorkHoldsCompletion(publishedRoster(harness)), - "the wakeup is still pending after the task notification's wake turn", - ); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect.each([{ emptyResult: true }, { emptyResult: false }])( - "an early wakeup after an idle task notification releases its hold (empty result: $emptyResult)", - ({ emptyResult }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified"), - text: "Run the build in the background and check back in two minutes.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - for (const frame of scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_notified", - uuids: ["00000000-0000-4000-8000-000000002601", "00000000-0000-4000-8000-000000002602"], - toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" }, - scheduledFor: DateTime.toEpochMillis(now) + 120_000, - })) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const assistantTools = ( + uuid: string, + tools: ReadonlyArray>, + parentToolUseId: string | null = null, + ) => + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: `msg_${uuid}`, + type: "message", + role: "assistant", + content: tools.map((tool) => ({ type: "tool_use", ...tool })), + stop_reason: "tool_use", + stop_sequence: null, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + }, + parent_tool_use_id: parentToolUseId, + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const toolResults = (uuid: string, toolUseIds: ReadonlyArray) => + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: toolUseIds.map((toolUseId) => ({ + type: "tool_result", + tool_use_id: toolUseId, + content: "ok", + })), + }, + parent_tool_use_id: null, + uuid, + session_id: WAKE_NATIVE_SESSION, + }); - yield* TestClock.adjust("10 seconds"); - yield* harness.offerAndWait(wakeNotification); - if (emptyResult) { - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002603", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); - } + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-1"), + text: "Plan the work.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000501", [ + { + id: "tool-todo-1", + name: "TodoWrite", + input: { todos: [{ content: "Inspect", status: "in_progress" }] }, + }, + ]), + ); + yield* Queue.offer( + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000501", [ + { + id: "tool-todo-1", + name: "TodoWrite", + input: { todos: [{ content: "Inspect", status: "in_progress" }] }, + }, + ]), + ); + yield* Queue.offer( + harness.sdkMessages, + toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, permissionMode: "bypassPermissions" }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "plan", + uuid: "00000000-0000-4000-8000-000000000508", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTurnInit, + uuid: "00000000-0000-4000-8000-000000000509", + permissionMode: "plan", + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000503", + result: "Todo recorded.", + }), + ); + yield* Queue.take(harness.terminalReceipts); - yield* TestClock.adjust("80 seconds"); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.awaitContinuation(1); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified-2"), - text: "check the build", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.offerAndWait( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000002604", - text: "Built.", - }), - ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002605", result: "Built." }), - ); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness))); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-2"), + providerTurnOrdinal: 2, + text: "Finish the plan.", + attachments: [], + }), + ); + const canUseTool = harness.getOpenedOptions()?.canUseTool; + assert.isFunction(canUseTool); + const planMarkdown = "# Ready to implement\n\n1. Ship it."; + yield* Effect.promise(() => + canUseTool!( + "ExitPlanMode", + { plan: planMarkdown }, + { + signal: new AbortController().signal, + toolUseID: "tool-exit-plan-1", + requestId: "request-exit-plan-1", + }, ), - ), - ); + ); + yield* Queue.offer( + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000504", [ + { + id: "tool-todo-2", + name: "TodoWrite", + input: { todos: [{ content: "Inspect", status: "completed" }] }, + }, + { id: "tool-exit-plan-1", name: "ExitPlanMode", input: { plan: planMarkdown } }, + ]), + ); + yield* Queue.offer( + harness.sdkMessages, + assistantTools( + "00000000-0000-4000-8000-000000000507", + [ + { + id: "tool-subagent-todo", + name: "TodoWrite", + input: { todos: [{ content: "Child-only work", status: "in_progress" }] }, + }, + ], + "tool-parent-agent", + ), + ); + yield* Queue.offer( + harness.sdkMessages, + toolResults("00000000-0000-4000-8000-000000000505", ["tool-todo-2", "tool-exit-plan-1"]), + ); + yield* Queue.offer( + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000509", [ + { + id: "tool-todo-3", + name: "TodoWrite", + input: { todos: [{ content: "Implement", status: "pending" }] }, + }, + ]), + ); + yield* Queue.offer( + harness.sdkMessages, + toolResults("00000000-0000-4000-8000-000000000510", ["tool-todo-3"]), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000506", + result: "Plan captured.", + }), + ); + yield* Queue.take(harness.terminalReceipts); - it.effect("a failed turn on a live Claude process keeps the pending wakeup's hold", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* startScheduleWakeupTurn( - harness, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002103", - result: "API Error: 529 overloaded", - subtype: "error_during_execution", - isError: true, - errors: ["API Error: 529 overloaded"], - terminalReason: "model_error", - }), - ); - assert.equal(harness.terminalEvents()[0]?.status, "failed"); - assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const items = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" ? [[String(event.turnItem.id), event.turnItem]] : [], + ), + ); + const plans = new Map( + harness.events.flatMap((event) => + event.type === "plan.updated" ? [[String(event.plan.id), event.plan]] : [], + ), + ); + const todoItems = [...items.values()].filter((item) => item.type === "todo_list"); + const proposedItems = [...items.values()].filter((item) => item.type === "proposed_plan"); + assert.lengthOf(todoItems, 3); + assert.equal(todoItems[1]?.status, "completed"); + assert.deepEqual(todoItems[1]?.steps, [ + { id: "todo-0", text: "Inspect", status: "completed" }, + ]); + assert.deepEqual(todoItems[2]?.steps, [ + { id: "todo-0", text: "Implement", status: "pending" }, + ]); + assert.equal(todoItems[1]?.runId, todoItems[2]?.runId); + assert.lengthOf(proposedItems, 1); + assert.equal( + proposedItems[0]?.type === "proposed_plan" && proposedItems[0].markdown, + planMarkdown, + ); + assert.isTrue( + [...items.values()].some( + (item) => item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-todo-2", + ), + ); + assert.isTrue( + [...items.values()].some( + (item) => + item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-exit-plan-1", + ), + ); + const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan"); + assert.equal(proposedPlan?.status, "active"); + assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]); + assert.deepEqual( + [...plans.values()].filter((plan) => plan.kind === "todo_list").map((plan) => plan.status), + ["superseded", "superseded", "active"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("ScheduleWakeup stop:true releases the pending wakeup's hold", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + type TaskToolCall = + | { name: "TaskCreate"; input: TaskCreateInput; output: TaskCreateOutput } + | { name: "TaskUpdate"; input: TaskUpdateInput; output: TaskUpdateOutput } + | { name: "TaskList"; input: Record; output: TaskListOutput }; + + function taskToolFrames( + tool: TaskToolCall, + nextUuid: () => string, + options?: { + parentToolUseId?: string; + isError?: boolean; + extraToolResult?: boolean; + nonExecutionKind?: string; + }, + ): ReadonlyArray { + const uuid = nextUuid(); + const toolUseId = `tool-${uuid}`; + const parentToolUseId = options?.parentToolUseId ?? null; + return [ + claudeSdkFrame({ + type: "assistant", + message: { + id: `msg_${uuid}`, + model: "claude-sonnet-4-6", + type: "message", + role: "assistant", + content: [{ type: "tool_use", id: toolUseId, name: tool.name, input: tool.input }], + stop_reason: "tool_use", + stop_sequence: null, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + }, + parent_tool_use_id: parentToolUseId, + uuid, + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: toolUseId, + content: + parentToolUseId !== null && tool.name === "TaskCreate" + ? `Task #${tool.output.task.id} created successfully: ${tool.output.task.subject}` + : parentToolUseId !== null && tool.name === "TaskUpdate" + ? tool.output.success + ? `Updated task #${tool.output.taskId} ${tool.output.updatedFields.join(", ")}` + : tool.output.error + : "Task tool finished.", + ...(options?.isError === undefined ? {} : { is_error: options.isError }), + }, + ...(options?.extraToolResult + ? [{ type: "tool_result", tool_use_id: "unrelated-tool", content: "ok" }] + : []), + ], + }, + // Like real Claude, subagent results carry only the text, no `tool_use_result`. + ...(parentToolUseId === null ? { tool_use_result: tool.output } : {}), + ...(options?.nonExecutionKind === undefined + ? {} + : { + tool_result_meta: [{ id: toolUseId, non_execution_kind: options.nonExecutionKind }], + }), + parent_tool_use_id: parentToolUseId, + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + }), + ]; + } + + const makeTaskToolHarnessWithOptions = (environment: NodeJS.ProcessEnv = {}) => + Effect.gen(function* () { + const configDir = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped({ + prefix: "t3-claude-tasks-", + }); + const path = yield* Path.Path; + const harness = yield* makeWakeHarnessWithOptions({ + environment: { + CLAUDE_CONFIG_DIR: path.relative(CLAUDE_TEST_RUNTIME_POLICY.cwd ?? ".", configDir), + ...environment, + }, + }); + let sequence = 600; + let turn = 0; + const nextUuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; + const startTurn = Effect.fnUntraced(function* () { + turn++; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-stop"), - text: "Schedule a wakeup, then cancel it.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-claude-task-tools-${turn}`), + providerTurnOrdinal: turn, + text: "Update the task list.", attachments: [], }), ); - const frames = [ - ...scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_set", - uuids: ["00000000-0000-4000-8000-000000002301", "00000000-0000-4000-8000-000000002302"], - toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false }, - scheduledFor: DateTime.toEpochMillis(now) + 60_000, - }), - ...scheduleWakeupFrames({ - toolUseId: "toolu_schedule_wakeup_stop", - uuids: ["00000000-0000-4000-8000-000000002303", "00000000-0000-4000-8000-000000002304"], - toolInput: { stop: true }, - scheduledFor: 0, + }); + const call = Effect.fnUntraced(function* ( + tool: TaskToolCall, + options?: Parameters[2], + ) { + for (const frame of taskToolFrames(tool, nextUuid, options)) { + yield* harness.offerAndWait(frame); + } + }); + const finishTurn = Effect.fnUntraced(function* () { + yield* harness.offerAndWait( + makeResultFrame({ uuid: nextUuid(), result: "Task list updated." }), + ); + return yield* Queue.take(harness.terminalReceipts); + }); + const plans = () => + harness.events.flatMap((event) => + event.type === "plan.updated" && event.plan.kind === "todo_list" ? [event.plan] : [], + ); + // Registers a running subagent so frames carrying its tool_use_id as + // parent_tool_use_id are processed instead of held for an unknown owner. + const launchSubagent = (toolUseId: string) => + harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: `task-${toolUseId}`, + tool_use_id: toolUseId, + description: "Work on tasks", + task_type: "local_agent", + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002305", result: "Cancelled." }), - ]; - for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); - yield* harness.awaitTerminal(1); - assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness))); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("Stop on a thread waiting for a ScheduleWakeup closes Claude and drops the hold", () => - Effect.scoped( - Effect.gen(function* () { - let closes = 0; - const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => - Effect.sync(() => { - closes++; - }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), - }); - yield* startScheduleWakeupTurn(harness); - const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; - assert.isTrue(backgroundWorkHoldsCompletion(settledThread?.pendingBackgroundTasks ?? [])); - // The wakeup alone must not refuse a model or mode change. - assert.isFalse(yield* harness.runtime.hasPendingBackgroundWorkForThread!(settledThread!)); - - yield* harness.runtime.interruptTurn({ - providerThread: settledThread ?? harness.providerThread, - providerTurnId: harness.terminalEvents()[0]!.providerTurnId, - requestRuntimeRestart: true, - }); + ); + return { configDir, startTurn, call, launchSubagent, finishTurn, plans }; + }); - assert.equal(closes, 1, "the wakeup lives in the CLI process, so Stop must close it"); - yield* harness.until(() => publishedRoster(harness).length === 0); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); + const makeTaskToolHarness = makeTaskToolHarnessWithOptions(); - it.effect.skipIf(process.getuid === undefined)( - "tails foreground Bash output under the physical cwd the query launched in", - () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-task-output-cwd-", - }); - const physicalCwd = path.join(root, "real", "project"); - const launchCwd = path.join(root, "link"); - yield* fileSystem.makeDirectory(physicalCwd, { recursive: true }); - yield* fileSystem.symlink(physicalCwd, launchCwd); - // The session opens in /workspace; a relative TMPDIR puts Claude's - // task files under whichever cwd the CLI was launched in. Linux, - // because Claude Code's macOS build ignores TMPDIR. - const harness = yield* makeWakeHarnessWithOptions({ environment: { TMPDIR: "../tmp" } }); - const now = yield* DateTime.now; - const toolUseId = "toolu_foreground_bash"; - const taskId = "foreground-bash-task"; - const tasks = path.join( - root, - "real", - "tmp", - `claude-${process.getuid?.()}`, - "project", - WAKE_NATIVE_SESSION, - "tasks", - ); - yield* fileSystem.makeDirectory(tasks, { recursive: true }); - yield* fileSystem.writeFileString(path.join(tasks, `${taskId}.output`), "line 1\n"); + const createTask = (id: string, subject: string): TaskToolCall => ({ + name: "TaskCreate", + input: { subject: `Requested ${subject}`, description: `Work on ${subject}.` }, + output: { task: { id, subject } }, + }); + const updateTask = (input: TaskUpdateInput, success = true): TaskToolCall => ({ + name: "TaskUpdate", + input, + output: { success, taskId: input.taskId, updatedFields: ["status"] }, + }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-task-output-cwd"), - text: "Run the build.", - attachments: [], - runtimePolicy: { ...CLAUDE_TEST_RUNTIME_POLICY, cwd: launchCwd }, - }), - ); - assert.equal(harness.getOpenedOptions()?.cwd, launchCwd); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - message: { + it.effect("persists a todo_list from inline Claude task-tool frames", () => + Effect.gen(function* () { + let sequence = 700; + const nextUuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; + const prompt = "Track a synthetic task."; + const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript({ + provider: "claudeAgent", + protocol: "claude-agent-sdk.query", + version: "1", + scenario: "claude_task_tools_inline", + metadata: { nativeSessionId: WAKE_NATIVE_SESSION }, + entries: [ + { + type: "expect_outbound", + frame: { + type: "query.open", + options: { model: "claude-sonnet-4-6", - id: "msg_foreground_bash", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: toolUseId, - name: "Bash", - input: { command: "vp run build", description: "Build" }, - }, - ], - stop_reason: null, - stop_sequence: null, - usage: { input_tokens: 1, output_tokens: 1 }, + tools: { type: "preset", preset: "claude_code" }, + permissionMode: "bypassPermissions", + allowDangerouslySkipPermissions: true, + settings: { showThinkingSummaries: true }, + sessionId: WAKE_NATIVE_SESSION, }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000a01", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: taskId, - tool_use_id: toolUseId, - description: "vp run build", - is_backgrounded: false, - task_type: "local_bash", - uuid: "00000000-0000-4000-8000-000000000a02", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "user", + }, + }, + { + type: "expect_outbound", + frame: { + type: "prompt.offer", message: { - role: "user", - content: [{ type: "tool_result", tool_use_id: toolUseId, content: "line 1" }], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000a03", - session_id: WAKE_NATIVE_SESSION, - tool_use_result: { stdout: "line 1\n", stderr: "", interrupted: false }, - }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a04", result: "Built." }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - - const chunks = harness.events.flatMap((event) => - event.type === "command_output.delta" ? [event.chunk] : [], - ); - assert.deepEqual(chunks, ["line 1\n"]); - }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), + type: "user", + message: { role: "user", content: prompt }, + parent_tool_use_id: null, + }, + }, + }, + ...[ + ...taskToolFrames(createTask("1", "Inspect"), nextUuid), + ...taskToolFrames(updateTask({ taskId: "1", status: "in_progress" }), nextUuid), + makeResultFrame({ uuid: nextUuid(), result: "Task recorded." }), + ].map((frame) => ({ type: "emit_inbound" as const, frame })), + ], + } satisfies ProviderReplayTranscript); + const materialized = yield* materializeFixtureInput({ + scenario: transcript.scenario, + fixtureInput: { steps: [{ type: "message", text: prompt }] }, + driver: ProviderDriverKind.make("claudeAgent"), + modelSelection: CLAUDE_MODEL_SELECTION, + }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime); + const scenario = { name: transcript.scenario, transcript, ...materialized }; + yield* Effect.gen(function* () { + const result = yield* runOrchestratorV2Scenario(scenario); + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + const plans = projection.plans.filter((plan) => plan.kind === "todo_list"); + assert.lengthOf(plans, 1); + assert.deepEqual( + plans[0]?.steps.map(({ id, text, status }) => ({ id, text, status })), + [{ id: "task-1", text: "Inspect", status: "running" }], + ); + assert.lengthOf( + projection.turnItems.filter((item) => item.type === "todo_list"), + 1, + ); + }).pipe( + Effect.provide(layerProviderReplay(scenario, ClaudeOrchestratorReplayHarness)), + provideDeterministicTestRuntime, + Effect.scoped, + ); + }), ); - it.effect("lets the native SDK acknowledge Stop before closing its own query", () => - Effect.scoped( + it.effect( + "projects TaskCreate and TaskUpdate into one plan per turn and supersedes it later", + () => Effect.gen(function* () { - let closes = 0; - let acknowledge = Effect.void; - const harness = yield* makeWakeHarnessWithOptions({ - interrupt: Effect.suspend(() => { - assert.equal(closes, 0); - return acknowledge; - }), - close: (messages) => - Effect.sync(() => { - closes++; - }).pipe(Effect.andThen(Queue.shutdown(messages))), - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("graceful-stop"), - text: "Work until stopped", - attachments: [], - }), - ); - acknowledge = harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000620", - result: "", - subtype: "error_during_execution", - errors: ["Error: Request was aborted."], - terminalReason: "aborted_streaming", - }), - ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "running", - ), - ); - const active = harness.events.find( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "running", - ); - if (active?.type !== "provider_turn.updated") - return yield* Effect.die("Missing running native turn"); - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: active.providerTurn.id, - requestRuntimeRestart: true, - }); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); - assert.equal(closes, 1); - assert.lengthOf(harness.terminalEvents(), 1); + const harness = yield* makeTaskToolHarness; + yield* harness.startTurn(); + yield* harness.call(createTask("1", "Inspect")); + yield* harness.call(createTask("2", "Implement")); + yield* harness.call(updateTask({ taskId: "1", status: "in_progress" })); + yield* harness.finishTurn(); + + const firstTurnPlans = harness.plans(); + assert.lengthOf(firstTurnPlans, 3); + assert.equal(new Set(firstTurnPlans.map((plan) => plan.id)).size, 1); + assert.deepEqual(firstTurnPlans.at(-1)?.steps, [ + { id: "task-1", text: "Inspect", status: "running" }, + { id: "task-2", text: "Implement", status: "pending" }, + ]); + const firstPlan = firstTurnPlans.at(-1)!; + + yield* harness.startTurn(); + yield* harness.call(updateTask({ taskId: "1", status: "completed", subject: "Inspected" })); + yield* harness.finishTurn(); + + const laterPlans = harness.plans().slice(firstTurnPlans.length); + assert.lengthOf(laterPlans, 2); + assert.equal(laterPlans[0]?.id, firstPlan.id); + assert.equal(laterPlans[0]?.status, "superseded"); + const newPlan = laterPlans[1]!; + assert.notEqual(newPlan.id, firstPlan.id); + assert.notEqual(newPlan.runId, firstPlan.runId); + assert.deepEqual(newPlan.steps, [ + { id: "task-1", text: "Inspected", status: "completed" }, + { id: "task-2", text: "Implement", status: "pending" }, + ]); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll( IdAllocator.layer, @@ -12257,139 +10644,124 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect("bounds an unacknowledged native Stop and settles its turn once", () => - Effect.scoped( - Effect.gen(function* () { - let closes = 0; - const interruptStarted = yield* Deferred.make(); - const harness = yield* makeWakeHarnessWithOptions({ - interrupt: Deferred.succeed(interruptStarted, undefined).pipe( - Effect.andThen(Effect.never), - ), - close: (messages) => - Effect.sync(() => { - closes++; - }).pipe(Effect.andThen(Queue.shutdown(messages))), - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("unacknowledged-stop"), - text: "Work until stopped", - attachments: [], - }), - ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "running", - ), - ); - const active = harness.events.find( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "running", - ); - if (active?.type !== "provider_turn.updated") - return yield* Effect.die("Missing running native turn"); - const stop = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: active.providerTurn.id, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkChild); - yield* Deferred.await(interruptStarted); - assert.equal(closes, 0); - yield* TestClock.adjust("11 seconds"); - yield* Fiber.join(stop); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); - assert.equal(closes, 1); - assert.lengthOf(harness.terminalEvents(), 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + it.effect("removes deleted tasks without resurrecting them on later updates or turns", () => + Effect.gen(function* () { + const harness = yield* makeTaskToolHarness; + yield* harness.startTurn(); + yield* harness.call(createTask("1", "Discard")); + yield* harness.call(createTask("2", "Keep")); + yield* harness.call(updateTask({ taskId: "1", status: "deleted" })); + yield* harness.call(updateTask({ taskId: "1", status: "pending" })); + yield* harness.finishTurn(); + assert.lengthOf(harness.plans(), 3); + assert.deepEqual(harness.plans().at(-1)?.steps, [ + { id: "task-2", text: "Keep", status: "pending" }, + ]); + + yield* harness.startTurn(); + yield* harness.call(updateTask({ taskId: "2", status: "in_progress" })); + yield* harness.finishTurn(); + assert.deepEqual(harness.plans().at(-1)?.steps, [ + { id: "task-2", text: "Keep", status: "running" }, + ]); + for (const plan of harness.plans().slice(2)) { + assert.isFalse(plan.steps.some((step) => step.id === "task-1")); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("preserves settled background work until an explicit stop", () => - Effect.scoped( + it.effect.each([ + { + tool: updateTask({ taskId: "2", status: "completed" }), + listId: undefined, + directory: WAKE_NATIVE_SESSION, + status: "completed", + }, + { + tool: createTask("2", "Implement"), + listId: " list/ID ", + directory: "list-ID", + status: "pending", + }, + ] as const)( + "recovers persisted tasks on the first $tool.name after restart", + ({ tool, listId, directory, status }) => Effect.gen(function* () { - let closes = 0; - const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => - Effect.sync(() => { - closes++; - }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), - }); - const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-settled-stop"); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId, - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; - assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); - assert.isTrue(yield* harness.hasPendingBackgroundWork); + const fs = yield* FileSystem.FileSystem; + const harness = yield* makeTaskToolHarnessWithOptions({ CLAUDE_CODE_TASK_LIST_ID: listId }); + const tasksDir = `${harness.configDir}/tasks/${directory}`; + yield* fs.makeDirectory(tasksDir, { recursive: true }); + // The native tool has already written its result before emitting the SDK frame. + for (const task of [ + { id: "1", subject: "Inspect", status: "completed" }, + { id: "2", subject: "Implement", status }, + { id: "3", subject: "Internal", status: "pending", metadata: { _internal: true } }, + ]) { + yield* fs.writeFileString( + `${tasksDir}/${task.id}.json`, + JSON.stringify({ description: "", blocks: [], blockedBy: [], ...task }), + ); + } + yield* fs.writeFileString(`${tasksDir}/4.json`, "{"); + yield* fs.makeDirectory(`${tasksDir}/5.json`); - const replacementAttempt = yield* harness.runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: { - ...harness.providerThread, - nativeThreadRef: { - ...harness.providerThread.nativeThreadRef!, - nativeId: "replacement-session", - }, - }, - now, - attemptId: RunAttemptId.make("attempt-claude-background-replacement"), - text: "Continue in a fresh session.", - attachments: [], - providerTurnOrdinal: 2, - }), - ) - .pipe(Effect.result); - assert.equal(replacementAttempt._tag, "Failure"); - assert.equal(closes, 0); - assert.isTrue(yield* harness.hasPendingBackgroundWork); + yield* harness.startTurn(); + yield* harness.call(tool); + assert.equal((yield* harness.finishTurn()).status, "completed"); + assert.deepEqual( + harness.plans().map((plan) => plan.steps), + [ + [ + { id: "task-1", text: "Inspect", status: "completed" }, + { id: "task-2", text: "Implement", status }, + ], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - yield* harness.runtime.interruptTurn({ - providerThread: settledThread ?? harness.providerThread, - providerTurnId: harness.terminalEvents()[0]!.providerTurnId, - requestRuntimeRestart: true, - }); + it.effect( + "publishes an empty task list when the first TaskUpdate after restart deletes the last task", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const harness = yield* makeTaskToolHarness; + const tasksDir = `${harness.configDir}/tasks/${WAKE_NATIVE_SESSION}`; + // Claude has removed the task file before emitting the SDK frame. + yield* fs.makeDirectory(tasksDir, { recursive: true }); + yield* fs.writeFileString(`${tasksDir}/.highwatermark`, "1"); - assert.equal(closes, 1, "Stop must close the CLI process that owns the task"); - yield* harness.until( - () => - (providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks?.length ?? 0) === 0, + yield* harness.startTurn(); + yield* harness.call(updateTask({ taskId: "1", status: "deleted" })); + assert.equal((yield* harness.finishTurn()).status, "completed"); + assert.deepEqual( + harness.plans().map((plan) => plan.steps), + [[]], ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll( IdAllocator.layer, @@ -12399,70 +10771,243 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("replaces task state with TaskList, including an empty list", () => + Effect.gen(function* () { + const harness = yield* makeTaskToolHarness; + yield* harness.startTurn(); + yield* harness.call(createTask("1", "Stale")); + yield* harness.call({ + name: "TaskList", + input: {}, + output: { + tasks: [ + { id: "2", subject: "Queued", status: "pending", blockedBy: [] }, + { id: "3", subject: "Working", status: "in_progress", blockedBy: [] }, + { id: "4", subject: "Done", status: "completed", blockedBy: [] }, + ], + }, + }); + yield* harness.call(updateTask({ taskId: "1", status: "in_progress" })); + yield* harness.call(updateTask({ taskId: "2", status: "in_progress" })); + yield* harness.call({ name: "TaskList", input: {}, output: { tasks: [] } }); + yield* harness.call(updateTask({ taskId: "2", status: "pending" })); + yield* harness.finishTurn(); + const plans = harness.plans(); + assert.lengthOf(plans, 4); + assert.deepEqual(plans[1]?.steps, [ + { id: "task-2", text: "Queued", status: "pending" }, + { id: "task-3", text: "Working", status: "running" }, + { id: "task-4", text: "Done", status: "completed" }, + ]); + assert.deepEqual(plans[2]?.steps, [ + { id: "task-2", text: "Queued", status: "running" }, + { id: "task-3", text: "Working", status: "running" }, + { id: "task-4", text: "Done", status: "completed" }, + ]); + assert.deepEqual(plans[3]?.steps, []); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect.each([ - { teardown: "before Stop" as const }, - { teardown: "during Stop's interrupt write" as const }, - ])("Stop with session teardown $teardown does not fail on the closed CLI", ({ teardown }) => + it.effect("applies subagent task tools to the parent turn's shared task list", () => Effect.gen(function* () { - const sessionScope = yield* Scope.make(); - let queryClosed = false; - const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => - Effect.sync(() => { - queryClosed = true; - }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), - interrupt: Effect.suspend(() => - teardown === "before Stop" ? Effect.void : Scope.close(sessionScope, Exit.void), - ).pipe( - Effect.andThen( - Effect.suspend(() => - queryClosed - ? Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "interrupt", - cause: new Error("ProcessTransport is not ready for writing"), - }), - ) - : Effect.void, - ), - ), + const harness = yield* makeTaskToolHarness; + yield* harness.startTurn(); + yield* harness.call(createTask("1", "Main task")); + yield* harness.launchSubagent("tool-parent-agent"); + const child = { parentToolUseId: "tool-parent-agent" }; + yield* harness.call(updateTask({ taskId: "1", status: "completed" }), child); + yield* harness.call(createTask("2", "Child task"), child); + yield* harness.call( + { + name: "TaskUpdate", + input: { taskId: "2", status: "completed" }, + output: { + success: false, + taskId: "2", + updatedFields: [], + error: "Tests must pass before completing.", + }, + }, + child, + ); + yield* harness.call(updateTask({ taskId: "2", status: "in_progress" }), { + ...child, + isError: true, + }); + // A cancelled call never ran, even without `is_error`. + yield* harness.call(updateTask({ taskId: "2", status: "completed" }), { + ...child, + nonExecutionKind: "cancelled", + }); + yield* harness.finishTurn(); + const plans = harness.plans(); + assert.lengthOf(plans, 3); + assert.equal(new Set(plans.map((plan) => plan.id)).size, 1); + assert.deepEqual(plans.at(-1)?.steps, [ + { id: "task-1", text: "Main task", status: "completed" }, + { id: "task-2", text: "Child task", status: "pending" }, + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), - }).pipe(Scope.provide(sessionScope)); + ), + ), + ); + + it.effect("recovers persisted tasks when a subagent's TaskList comes first", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const harness = yield* makeTaskToolHarness; + const tasksDir = `${harness.configDir}/tasks/${WAKE_NATIVE_SESSION}`; + yield* fs.makeDirectory(tasksDir, { recursive: true }); + yield* fs.writeFileString( + `${tasksDir}/1.json`, + JSON.stringify({ id: "1", subject: "Inspect", status: "pending", blockedBy: [] }), + ); + + yield* harness.startTurn(); + yield* harness.launchSubagent("tool-parent-agent"); + yield* harness.call( + { name: "TaskList", input: {}, output: { tasks: [] } }, + { parentToolUseId: "tool-parent-agent" }, + ); + yield* harness.call(updateTask({ taskId: "1", status: "completed" })); + yield* harness.finishTurn(); + assert.deepEqual(harness.plans().at(-1)?.steps, [ + { id: "task-1", text: "Inspect", status: "completed" }, + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + // regression: #14964 structured task output attaches to exactly one tool result + it.effect("does not associate structured task output with multiple tool results", () => + Effect.gen(function* () { + const harness = yield* makeTaskToolHarness; + yield* harness.startTurn(); + yield* harness.call(createTask("1", "Ambiguous"), { extraToolResult: true }); + yield* harness.finishTurn(); + assert.deepEqual(harness.plans(), []); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("resolves API retries on resumed assistant activity", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-closed-scope-stop"); - const idAllocator = yield* IdAllocator.IdAllocatorV2; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId, - text: "Hand this thread off to a worktree.", + attemptId: RunAttemptId.make("attempt-claude-api-retry"), + text: "Open github.com.", attachments: [], }), ); - // A workspace handoff detaches the session, closing its scope while the turn streams. - if (teardown === "before Stop") { - yield* Scope.close(sessionScope, Exit.void); - assert.isTrue(queryClosed); - } - const interrupted = yield* Effect.exit( - harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }), - requestRuntimeRestart: true, + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "api_retry", + attempt: 2, + max_retries: 10, + retry_delay_ms: 1_500, + error_status: 529, + error: "overloaded", + uuid: "00000000-0000-4000-8000-000000000201", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const retryItems = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "error" && + event.turnItem.retry !== undefined + ? [event.turnItem] + : [], + ); + yield* harness.until(() => retryItems().length === 1); + const runningRetry = retryItems()[0]; + assert.equal(runningRetry?.status, "running"); + assert.equal(runningRetry?.failure.code, "api_error_529"); + assert.deepEqual(runningRetry?.retry, { + attempt: 2, + maxAttempts: 10, + retryDelayMs: 1_500, + }); + + // The stream starting again settles the retry before any assistant message completes. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "stream_event", + event: { type: "message_start", message: { id: "api-retry-recovered-message" } }, + parent_tool_use_id: null, + session_id: WAKE_NATIVE_SESSION, + uuid: "00000000-0000-4000-8000-000000000204", + }), + ); + yield* harness.until(() => retryItems().length === 2); + assert.lengthOf(harness.terminalEvents(), 0); + const recoveredRetry = retryItems()[1]; + assert.equal(recoveredRetry?.id, runningRetry?.id); + assert.equal(recoveredRetry?.status, "completed"); + assert.equal(recoveredRetry?.title, "Provider recovered"); + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000202", + text: "Opening GitHub.", + }), + ); + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000203", + result: "Opened GitHub.", }), ); - - assert.isTrue(Exit.isSuccess(interrupted), String(interrupted)); - assert.isTrue(queryClosed); + yield* harness.awaitTerminal(1); }).pipe( Effect.provide( Layer.mergeAll( @@ -12475,313 +11020,48 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("a settled Stop leaves a turn that replaced the closing process alone", () => - Effect.scoped( + it.effect.each(["api_error", "overloaded_status"] as const)( + "fails a success-shaped Claude result with %s", + (terminalReason) => Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-settled-stop-replaced-", - }); - const processQueues: Array> = []; - const firstCloseRequested = yield* Deferred.make(); - const events: Array = []; - const continuationRequests: Array = - []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }).pipe(Effect.andThen(changes.notify)), - }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - const isFirstProcess = processQueues.length === 0; - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: isFirstProcess - ? Deferred.succeed(firstCloseRequested, undefined).pipe(Effect.asVoid) - : Queue.shutdown(sdkMessages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-settled-stop-replaced"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-settled-stop"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe(Effect.andThen(changes.notify)), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const terminals = () => events.filter((event) => event.type === "turn.terminal"); + const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(processQueues[0]!, wakeTaskStarted); - yield* Queue.offer(processQueues[0]!, turnOneResult); - yield* changes.until(() => terminals().length === 1); - const settledThread = providerThreadRosterEvents(events).at(-1)?.providerThread; - const settledTurn = terminals()[0]; - assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); - - const stop = yield* runtime - .interruptTurn({ - providerThread: settledThread ?? providerThread, - providerTurnId: settledTurn!.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(firstCloseRequested); - - yield* runtime.startTurn( + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, + threadId: harness.threadId, + providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-b"), - text: "Start another background build.", + attemptId: RunAttemptId.make("attempt-structured-terminal-failure"), + text: "Complete the task.", attachments: [], - providerTurnOrdinal: 2, - modelSelection: { - ...CLAUDE_TEST_MODEL_SELECTION, - model: "claude-haiku-4-5-20251001", - }, - }), - ); - assert.lengthOf(processQueues, 2); - const replacementTaskId = "replacement-task"; - yield* Queue.offer( - processQueues[1]!, - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: replacementTaskId, - uuid: "00000000-0000-4000-8000-000000000905", - }), - ); - yield* changes.until( - () => - providerThreadRosterEvents(events).at(-1)?.providerThread.pendingBackgroundTasks?.[0] - ?.taskId === replacementTaskId, - ); - - yield* Queue.shutdown(processQueues[0]!); - yield* Fiber.join(stop); - assert.isTrue(yield* hasPendingBackgroundWork); - yield* yieldTicks(50); - const latestThread = providerThreadRosterEvents(events).at(-1)?.providerThread; - assert.equal(latestThread?.status, "active"); - assert.deepEqual( - latestThread?.pendingBackgroundTasks?.map((task) => task.taskId), - [replacementTaskId], - ); - - yield* Queue.offer( - processQueues[1]!, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000906", - result: "Started another build.", - }), - ); - yield* changes.until(() => terminals().length === 2); - yield* Queue.offer( - processQueues[1]!, - claudeSdkFrame({ - ...wakeNotification, - task_id: replacementTaskId, - uuid: "00000000-0000-4000-8000-000000000907", }), ); yield* Queue.offer( - processQueues[1]!, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000908", - text: WAKE_ASSISTANT_TEXT, - }), - ); - yield* changes.until(() => continuationRequests.length === 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - const openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame = Effect.fnUntraced(function* ( - name: string, - ) { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: `t3-claude-v2-${name}-`, - }); - const deadStreamEnded = yield* Deferred.make(); - let opened = 0; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - // startTurn reads the auto-compact window from settings between opening the query and - // attaching the turn; holding that read until the CLI's stream has ended pins the race. - fileSystem: { - ...fileSystem, - readFileString: (filePath, encoding) => - opened === 1 && filePath.endsWith("settings.json") - ? Deferred.await(deadStreamEnded).pipe( - Effect.andThen(fileSystem.readFileString(filePath, encoding)), - ) - : fileSystem.readFileString(filePath, encoding), - }, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { offer: () => Effect.void }, - queryRunner: { - allocateSessionId: Effect.succeed(`native-${name}`), - open: () => - Effect.gen(function* () { - opened += 1; - const sdkMessages = yield* Queue.unbounded(); - return { - // The first CLI exits without writing a frame. - messages: - opened === 1 - ? Stream.empty.pipe(Stream.ensuring(Deferred.succeed(deadStreamEnded, undefined))) - : Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make(`thread-${name}`); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make(`provider-session-${name}`), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const now = yield* DateTime.now; - const turnInput = (attempt: string, providerTurnOrdinal: number) => - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make(`attempt-${name}-${attempt}`), - text: "Continue with the plan.", - attachments: [], - providerTurnOrdinal, - }); - return { runtime, turnInput }; - }); - - it.effect("fails a turn whose Claude query ends before its first frame", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame( - "claude-query-dies-before-frame", + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000205", + result: "Provider failure details.", + isError: false, + ...(terminalReason === "overloaded_status" + ? { apiErrorStatus: 529 } + : { terminalReason }), + }), ); - const started = yield* harness.runtime - .startTurn(harness.turnInput("a", 1)) - .pipe(Effect.exit); - assert.isTrue( - Exit.isFailure(started), - "a turn whose Claude query ended before its first frame started running on the dead query", + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.isNotEmpty(terminal.failure.message); + assert.equal(terminal.failure.class, "provider_error"); + assert.isFalse( + harness.events.some( + (event) => + event.type === "message.updated" && + event.message.text === "Provider failure details.", + ), ); - if (Exit.isFailure(started)) { - assert.include( - Cause.pretty(started.cause), - "Claude provider query ended before the turn could start.", - ); - } - const followUp = yield* harness.runtime - .startTurn(harness.turnInput("b", 2)) - .pipe(Effect.exit); - assert.isTrue( - Exit.isSuccess(followUp), - `the turn whose query ended before its first frame is still active: ${ - Exit.isFailure(followUp) ? Cause.pretty(followUp.cause) : "" - }`, + assert.equal( + terminal.failure.code, + terminalReason === "overloaded_status" ? "api_error_529" : terminalReason, ); }).pipe( Effect.provide( @@ -12793,507 +11073,109 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), - ); - - it.effect( - "clears the replaced sibling native thread roster when openQuery switches processes", - () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-sibling-replace-", - }); - const nativeIds = ["native-thread-roster-a", "native-thread-roster-b"] as const; - let allocateIndex = 0; - // A shared queue would hide sibling process death on replacement. - const processQueues: Array<{ - readonly nativeThreadId: string; - readonly queue: Queue.Queue; - }> = []; - const events: Array = []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { - offer: () => Effect.void, - }, - queryRunner: { - allocateSessionId: Effect.sync(() => { - const next = - nativeIds[allocateIndex] ?? `native-thread-roster-extra-${allocateIndex}`; - allocateIndex += 1; - return next; - }), - open: (openInput) => - Effect.gen(function* () { - const nativeThreadId = openInput.options.sessionId ?? openInput.options.resume; - if (typeof nativeThreadId !== "string" || nativeThreadId.length === 0) { - return yield* Effect.die("openQuery must supply a native session id"); - } - const queue = yield* Queue.unbounded(); - processQueues.push({ nativeThreadId, queue }); - return { - messages: Stream.fromQueue(queue), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(queue), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const appThreadA = ThreadId.make("thread-claude-roster-a"); - const appThreadB = ThreadId.make("thread-claude-roster-b"); - const runtime = yield* adapter.openSession({ - threadId: appThreadA, - providerSessionId: ProviderSessionId.make("provider-session-claude-sibling-replace"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThreadA = yield* runtime.ensureThread({ - threadId: appThreadA, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThreadB = yield* runtime.ensureThread({ - threadId: appThreadB, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - assert.notEqual( - providerThreadA.nativeThreadRef?.nativeId, - providerThreadB.nativeThreadRef?.nativeId, - ); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe(Effect.andThen(changes.notify)), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "Claude adapter runtime must expose hasPendingBackgroundWork.", - ); - } - if (runtime.hasPendingBackgroundWorkForThread === undefined) { - return yield* Effect.die( - "Claude adapter runtime must expose hasPendingBackgroundWorkForThread.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const hasPendingBackgroundWorkForThread = runtime.hasPendingBackgroundWorkForThread; - const now = yield* DateTime.now; - const taskA = "task-roster-a"; - const taskB = "task-roster-b"; - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: appThreadA, - providerThread: providerThreadA, - now, - attemptId: RunAttemptId.make("attempt-roster-iso-a"), - text: "Background work on A.", - attachments: [], - }), - ); - assert.equal(processQueues.length, 1); - const processA = processQueues[0]!; - yield* Queue.offer( - processA.queue, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: taskA, - tool_use_id: "toolu-roster-a", - description: "work on A", - is_backgrounded: true, - task_type: "local_bash", - uuid: "00000000-0000-4000-8000-000000000301", - session_id: nativeIds[0], - }), - ); - yield* Queue.offer( - processA.queue, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000302", - result: "A settled with background work.", - }), - ); - yield* changes.until(() => - events.some( - (event) => - event.type === "turn.terminal" && - event.providerThreadId === providerThreadA.id && - event.status === "completed", - ), - ); - const rosterAAfterSettle = providerThreadRosterEvents(events).findLast( - (event) => event.providerThread.id === providerThreadA.id, - )?.providerThread.pendingBackgroundTasks; - assert.deepEqual(rosterAAfterSettle ?? [], [ - { - taskId: taskA, - description: "work on A", - kind: "command", - nativeItemId: "toolu-roster-a", - }, - ]); - assert.isTrue(yield* hasPendingBackgroundWork); - assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: appThreadB, - providerThread: { ...providerThreadB, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-roster-iso-b"), - text: "Background work on B.", - attachments: [], - }), - ); - assert.equal(processQueues.length, 2); - yield* changes.until(() => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.id === providerThreadA.id && - event.providerThread.status === "idle" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, - ), - ); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - - const processB = processQueues[1]!; - yield* Queue.offer( - processB.queue, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: taskB, - tool_use_id: "toolu-roster-b", - description: "work on B", - is_backgrounded: true, - task_type: "local_bash", - uuid: "00000000-0000-4000-8000-000000000303", - session_id: nativeIds[1], - }), - ); - yield* changes.until(() => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.id === providerThreadB.id && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, - ), - ); - assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - assert.isTrue(yield* hasPendingBackgroundWork); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - - yield* Queue.offer( - processB.queue, - claudeSdkFrame({ - type: "result", - subtype: "error_during_execution", - duration_ms: 10, - duration_api_ms: 10, - is_error: true, - num_turns: 1, - result: "B failed", - stop_reason: "end_turn", - total_cost_usd: 0, - usage: { - input_tokens: 1, - output_tokens: 1, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - }, - modelUsage: {}, - permission_denials: [], - errors: ["B failed"], - terminal_reason: "model_error", - uuid: "00000000-0000-4000-8000-000000000304", - session_id: nativeIds[1], - }), - ); - yield* changes.until(() => - events.some( - (event) => - event.type === "turn.terminal" && - event.providerThreadId === providerThreadB.id && - event.status === "failed", - ), - ); - - const rosterBAfterFail = providerThreadRosterEvents(events).findLast( - (event) => event.providerThread.id === providerThreadB.id, - )?.providerThread.pendingBackgroundTasks; - assert.deepEqual(rosterBAfterFail ?? [], []); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), ); - it.effect.each(["full-access", "approval-required"] as const)( - "keeps a queued wake turn's tool callback with its continuation in %s mode", - (runtimeMode) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode, - interactionMode: "default", - cwd: "/workspace", - }); - const firstAttempt = RunAttemptId.make("attempt-claude-wake-callback-1"); - const userAttempt = RunAttemptId.make("attempt-claude-wake-callback-2"); - const continuationAttempt = RunAttemptId.make("attempt-claude-wake-callback-3"); - const planToolUseId = "toolu_01WakePlanExitPlanMode"; - const planMarkdown = "# Wake plan\n\n1. Report the background result."; - const stamp = (frame: SDKMessage, promptIndex: number) => - claudeSdkFrame({ - ...frame, - user_message_uuid: harness.promptUuid(promptIndex), - }); - const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`); - const planToolUse = claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_wake_plan", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: planToolUseId, - name: "ExitPlanMode", - input: { plan: planMarkdown }, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000741", - session_id: WAKE_NATIVE_SESSION, - }); - const planToolResult = claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: planToolUseId, - content: - "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", - is_error: true, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000742", - session_id: WAKE_NATIVE_SESSION, - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: firstAttempt, - text: "Run the build in the background.", - attachments: [], - runtimePolicy, - }), - ); - yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0)); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000740", result: "STARTED" }), - 0, - ), - ); - yield* harness.awaitTerminal(1); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: userAttempt, - text: "Reply with exactly: USER_REPLY", - attachments: [], - runtimePolicy, - providerTurnOrdinal: 2, - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - // The SDK asks for permission only after streaming the tool_use. - yield* harness.offerAndWait(planToolUse); - const canUseTool = harness.getOpenedOptions()?.canUseTool; - assert.isFunction(canUseTool); - const callback = yield* Effect.promise(() => - canUseTool!( - "ExitPlanMode", - { plan: planMarkdown }, - { - signal: new AbortController().signal, - toolUseID: planToolUseId, - requestId: "request-wake-plan", - }, - ), - ); - assert.equal(callback?.behavior, "deny"); - assert.include( - callback?.behavior === "deny" ? callback.message : "", - "The client captured your proposed plan", - ); - yield* Queue.offer(harness.sdkMessages, planToolResult); - yield* Queue.offer(harness.sdkMessages, wakeResult); - yield* harness.awaitContinuation(1); - - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000743", - text: "USER_REPLY", - }), - 1, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000744", - result: "USER_REPLY", - }), - 1, - ), - ); - yield* harness.awaitTerminal(2); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: continuationAttempt, - text: "Background task completed.", - attachments: [], - runtimePolicy, - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.awaitTerminal(3); - - const latestItems = new Map( - harness.events.flatMap((event) => - event.type === "turn_item.updated" - ? [[String(event.turnItem.id), event.turnItem]] - : [], - ), - ); - const planTool = [...latestItems.values()].find( - (item) => - item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === planToolUseId, - ); - const proposedPlans = [...latestItems.values()].filter( - (item) => item.type === "proposed_plan", - ); - const plans = harness.events.flatMap((event) => - event.type === "plan.updated" && event.plan.kind === "proposed_plan" - ? [event.plan] - : [], - ); - const planToolRuns = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === planToolUseId && - event.turnItem.type === "dynamic_tool" - ? [event.turnItem.runId] - : [], - ); - assert.isNotEmpty(planToolRuns); - assert.isTrue(planToolRuns.every((runId) => runId === runOf(continuationAttempt))); - assert.equal(planTool?.runId, runOf(continuationAttempt)); - assert.lengthOf(proposedPlans, 1); - assert.equal(proposedPlans[0]?.runId, runOf(continuationAttempt)); - assert.isTrue(plans.length > 0); - assert.isTrue(plans.every((plan) => plan.runId === runOf(continuationAttempt))); - const userRunItems = [...latestItems.values()].filter( - (item) => item.runId === runOf(userAttempt), - ); - assert.deepEqual( - userRunItems.map((item) => item.type), - ["assistant_message"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + // Context exhaustion reports blocking_limit even when the rate-limit window is allowed. + it.effect.each([ + { + windowStatus: "allowed", + expectedClass: "provider_error", + expectedMessage: "Claude stopped: the prompt exceeds the model's context window.", + }, + { + windowStatus: "rejected", + expectedClass: "usage_limit", + expectedMessage: "Claude usage limit reached. Send the message again once the limit resets.", + }, + ] as const)( + "classifies blocking_limit by its rate-limit evidence ($windowStatus window)", + ({ windowStatus, expectedClass, expectedMessage }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-blocking-limit-${windowStatus}`), + text: "Continue.", + attachments: [], + }), + ); + yield* Queue.offerAll(harness.sdkMessages, [ + claudeSdkFrame({ + type: "rate_limit_event", + rate_limit_info: { status: windowStatus, rateLimitType: "five_hour" }, + uuid: "00000000-0000-4000-8000-000000000660", + session_id: WAKE_NATIVE_SESSION, + }), + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000661", + error: "invalid_request", + text: "Prompt is too long", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000662", + result: "Prompt is too long", + isError: true, + numTurns: 189, + terminalReason: "blocking_limit", + }), + ]); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, expectedClass); + assert.include(terminal.failure.message, expectedMessage); + assert.equal(terminal.failure.code, "blocking_limit"); + if (expectedClass === "provider_error") { + assert.include(terminal.failure.message, "/compact"); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("stores a Bash result's stdout and stderr as command output", () => - Effect.scoped( + const providerThreadRosterEvents = ( + events: ReadonlyArray, + ) => + events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_thread.updated" } + > => event.type === "provider_thread.updated", + ); + + it.effect( + "uses task_started as an incremental roster fallback, keeps its tool call, and clears internal work on empty snapshot", + () => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-bash-output"); - const bashToolUseId = "toolu_01BashOutput"; + const emptyRoster = claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000202", + session_id: WAKE_NATIVE_SESSION, + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId, - text: "Run it.", + attemptId: RunAttemptId.make("attempt-claude-roster-fallback"), + text: "Run the build in the background.", attachments: [], }), ); @@ -13303,338 +11185,538 @@ describe("ClaudeAdapterV2 background wake turns", () => { type: "assistant", message: { model: "claude-sonnet-4-6", - id: "msg_bash_output", + id: "msg_background_command", type: "message", role: "assistant", content: [ { type: "tool_use", - id: bashToolUseId, + id: WAKE_TOOL_USE_ID, name: "Bash", - input: { command: "git status" }, + input: { + command: "python3 audit.py > audit.log 2>&1", + run_in_background: true, + }, }, ], }, parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000790", + uuid: "background-command-launch", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + + const afterStart = providerThreadRosterEvents(harness.events).filter( + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + assert.isAtLeast(afterStart.length, 1); + const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]; + assert.equal(started?.taskId, WAKE_TASK_ID); + assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID); + + const command = harness.events.find( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.nativeItemRef?.nativeId === WAKE_TOOL_USE_ID, + ); + assert.equal(command?.type, "turn_item.updated"); + if (command?.type !== "turn_item.updated") return; + const details = { + command: "python3 audit.py > audit.log 2>&1", + itemId: command.turnItem.id, + }; + assert.deepInclude(afterStart.at(-1)?.providerThread.pendingBackgroundTasks?.[0], details); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [{ task_id: WAKE_TASK_ID, task_type: "local_bash", description: "Audit" }], + uuid: "background-command-snapshot", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.deepInclude( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks?.[0], + details, + ); + + // A foreground command that later moves to the background keeps its tool call too. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "moved-shell", + tool_use_id: "toolu_moved_shell", + description: "Foreground build", + is_backgrounded: false, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000204", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { + task_id: "subagent-shell", + task_type: "local_bash", + description: "sleep 150", + parent_task_id: "agent-1", + }, + { + task_id: WAKE_TASK_ID, + task_type: "local_bash", + description: WAKE_TASK_DESCRIPTION, + }, + { + task_id: "moved-shell", + task_type: "local_bash", + description: "Foreground build", + }, + ], + uuid: "00000000-0000-4000-8000-000000000203", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until(() => + providerThreadRosterEvents(harness.events).some( + (event) => + event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1" && + event.providerThread.pendingBackgroundTasks[1]?.nativeItemId === WAKE_TOOL_USE_ID && + event.providerThread.pendingBackgroundTasks[2]?.nativeItemId === "toolu_moved_shell", + ), + ); + + yield* harness.offerAndWait(emptyRoster); + assert.include( + ( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks ?? [] + ).map((task) => task.taskId), + WAKE_TASK_ID, + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("holds only the background tasks the agent marks awaited, until they end", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + throw new Error("Claude adapter runtime must expose awaitBackgroundTasks."); + } + const roster = (tasks: ReadonlyArray, uuid: string) => + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: tasks.map((taskId) => ({ + task_id: taskId, + task_type: "local_bash", + description: taskId, + })), + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const nextRoster = Effect.fn("nextRoster")(function* ( + matches: (tasks: ReadonlyArray) => boolean, + ) { + while (true) { + const { providerThread } = yield* Queue.take(harness.providerThreadReceipts); + const tasks = providerThread.pendingBackgroundTasks ?? []; + if (matches(tasks)) return tasks; + } + }); + const marks = (tasks: ReadonlyArray) => + tasks.map((task) => [task.taskId, task.awaited === true]); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-awaited-roster"), + text: "Run the tests in the background and the dev server.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + roster([WAKE_TASK_ID, "dev-server"], "00000000-0000-4000-8000-000000000301"), + ); + yield* nextRoster((tasks) => tasks.length === 2); + + const marked = yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [WAKE_TASK_ID, "already-finished"], + awaited: true, + }); + assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]); + assert.deepStrictEqual( + marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))), + [ + [WAKE_TASK_ID, true], + ["dev-server", false], + ], + ); + // A replacing level rebuilds every entry; the mark must survive it. + yield* Queue.offer( + harness.sdkMessages, + roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000302"), + ); + assert.deepStrictEqual( + marks(yield* nextRoster((tasks) => tasks[0]?.taskId === "dev-server")), + [ + ["dev-server", false], + [WAKE_TASK_ID, true], + ], + ); + + // Once the task ends, a reused id starts unmarked. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ ...wakeNotification, uuid: "00000000-0000-4000-8000-000000000303" }), + ); + yield* nextRoster((tasks) => tasks.length === 1); + yield* Queue.offer( + harness.sdkMessages, + roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"), + ); + assert.deepStrictEqual(marks(yield* nextRoster((tasks) => tasks.length === 2)), [ + ["dev-server", false], + [WAKE_TASK_ID, false], + ]); + + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["dev-server"], + awaited: true, + }); + assert.deepStrictEqual( + marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))), + [ + ["dev-server", true], + [WAKE_TASK_ID, false], + ], + ); + const released = yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["dev-server"], + awaited: false, + }); + assert.deepStrictEqual(released.matched, ["dev-server"]); + assert.deepStrictEqual( + marks(yield* nextRoster((tasks) => !tasks.some((task) => task.awaited === true))), + [ + ["dev-server", false], + [WAKE_TASK_ID, false], + ], + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* Queue.take(harness.terminalReceipts); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("keeps a running Claude monitor typed after many newer monitors end", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + let frameNumber = 0; + const nextUuid = () => `00000000-0000-4000-8000-${String(++frameNumber).padStart(12, "0")}`; + const monitorFrames = (index: number) => { + const taskId = `monitor-task-${index}`; + const toolUseId = `toolu_monitor_${index}`; + const description = `Monitor ${index}`; + return { + taskId, + start: [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: `msg_monitor_${index}`, + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: toolUseId, + name: "Monitor", + input: { description, command: "sleep 8 && echo MONITOR_DONE" }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }, + parent_tool_use_id: null, + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: toolUseId, + description, + is_backgrounded: true, + task_type: "local_bash", + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: toolUseId, + content: `Monitor started (task ${taskId}).`, + }, + ], + }, + parent_tool_use_id: null, + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { taskId, persistent: false }, + }), + ], + end: claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: taskId, + tool_use_id: toolUseId, + status: "completed", + output_file: `/tmp/claude-replay/tasks/${taskId}.output`, + summary: `Monitor "${description}" stream ended`, + uuid: nextUuid(), session_id: WAKE_NATIVE_SESSION, }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { type: "tool_result", tool_use_id: bashToolUseId, content: "On branch main" }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000791", - session_id: WAKE_NATIVE_SESSION, - tool_use_result: { - stdout: "On branch main", - stderr: "warning: dirty", - interrupted: false, - isImage: false, + }; + }; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-many-monitors"), + text: "Watch the deploy, then re-arm short watches.", + attachments: [], + }), + ); + const longRunning = monitorFrames(0); + for (const frame of longRunning.start) { + yield* Queue.offer(harness.sdkMessages, frame); + } + for (let index = 1; index <= 65; index++) { + const monitor = monitorFrames(index); + for (const frame of monitor.start) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.offer(harness.sdkMessages, monitor.end); + } + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { + task_id: longRunning.taskId, + task_type: "local_bash", + description: "Monitor 0", }, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000792", result: "Done." }), - ); - yield* harness.awaitTerminal(1); + ], + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: nextUuid(), result: "Watching." }), + ); + yield* harness.awaitTerminal(1); - const bash = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === bashToolUseId, - ); - assert.equal( - bash?.type === "turn_item.updated" && bash.turnItem.type === "command_execution" - ? bash.turnItem.output - : undefined, - "On branch main\nwarning: dirty", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks; + assert.deepEqual(roster, [ + { + taskId: longRunning.taskId, + kind: "monitor", + description: "Monitor 0", + nativeItemId: "toolu_monitor_0", + }, + ]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect.each([ - { - case: "an Edit", - toolName: "Edit", - toolInput: { - file_path: "/workspace/src/math.ts", - old_string: " return a - b;", - new_string: " return a + b;", - }, - toolUseResult: { - filePath: "/workspace/src/math.ts", - oldString: " return a - b;", - newString: " return a + b;", - originalFile: "export function add(a: number, b: number) {\n return a - b;\n}\n", - structuredPatch: [ - { - oldStart: 1, - oldLines: 3, - newStart: 1, - newLines: 3, - lines: [ - " export function add(a: number, b: number) {", - "- return a - b;", - "+ return a + b;", - " }", - ], - }, + const scheduleWakeupFrames = (input: { + readonly toolUseId: string; + readonly uuids: readonly [string, string]; + readonly toolInput: Record; + readonly scheduledFor: number; + }) => [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: `msg_${input.toolUseId}`, + type: "message", + role: "assistant", + content: [ + { type: "tool_use", id: input.toolUseId, name: "ScheduleWakeup", input: input.toolInput }, ], - userModified: false, - replaceAll: false, + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, }, - diffStr: - "--- /workspace/src/math.ts\n+++ /workspace/src/math.ts\n@@ -1,3 +1,3 @@\n export function add(a: number, b: number) {\n- return a - b;\n+ return a + b;\n }\n", - }, - { - case: "a Write that creates a file", - toolName: "Write", - toolInput: { file_path: "/workspace/notes.md", content: "# Notes\n\nShip it.\n" }, - toolUseResult: { - type: "create", - filePath: "/workspace/notes.md", - content: "# Notes\n\nShip it.\n", - structuredPatch: [], - originalFile: null, - userModified: false, + parent_tool_use_id: null, + uuid: input.uuids[0], + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [{ type: "tool_result", tool_use_id: input.toolUseId, content: "Scheduled." }], }, - diffStr: "--- /dev/null\n+++ /workspace/notes.md\n@@ -0,0 +1,3 @@\n+# Notes\n+\n+Ship it.\n", - }, - { - case: "a Write that creates an empty file", - toolName: "Write", - toolInput: { file_path: "/workspace/.keep", content: "" }, - toolUseResult: { - type: "create", - filePath: "/workspace/.keep", - content: "", - structuredPatch: [], - originalFile: null, - userModified: false, + parent_tool_use_id: null, + uuid: input.uuids[1], + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { + scheduledFor: input.scheduledFor, + clampedDelaySeconds: 60, + wasClamped: false, }, - diffStr: undefined, - }, - ])("stores the diff panel patch for $case", (testCase) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const toolUseId = `toolu_01${testCase.toolName}Patch`; + }), + ]; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-claude-${testCase.toolName}-patch`), - text: "Change it.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: `msg_${testCase.toolName}_patch`, - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: toolUseId, - name: testCase.toolName, - input: testCase.toolInput, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000793", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: toolUseId, - content: `The file ${testCase.toolInput.file_path} has been updated successfully.`, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000794", - session_id: WAKE_NATIVE_SESSION, - tool_use_result: testCase.toolUseResult, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000795", result: "Done." }), - ); - yield* harness.awaitTerminal(1); + const startScheduleWakeupTurn = Effect.fnUntraced(function* ( + harness: Effect.Success, + result = makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002103", + result: "Scheduled.", + }), + ) { + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-1"), + text: "Wake up in a minute.", + attachments: [], + }), + ); + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_1", + uuids: ["00000000-0000-4000-8000-000000002101", "00000000-0000-4000-8000-000000002102"], + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false }, + scheduledFor: DateTime.toEpochMillis(now) + 60_000, + })) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.offer(harness.sdkMessages, result); + yield* harness.awaitTerminal(1); + }); - const fileChange = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === toolUseId, - ); - assert.deepEqual( - fileChange?.type === "turn_item.updated" && fileChange.turnItem.type === "file_change" - ? { diffStr: fileChange.turnItem.diffStr } - : undefined, - { diffStr: testCase.diffStr }, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); + const publishedRoster = (harness: Effect.Success) => + providerThreadRosterEvents(harness.events).at(-1)?.providerThread.pendingBackgroundTasks ?? []; - it.effect("answers an approval a held wake turn raises without waiting for the echo", () => - Effect.scoped( + it.effect.each([ + { rescheduled: false, firedAfter: "60 seconds" }, + { rescheduled: true, firedAfter: "60 seconds" }, + // Claude fires one-shot wakeups early, so the wake init can precede scheduledFor. + { rescheduled: false, firedAfter: "30 seconds" }, + ] as const)( + "a fired ScheduleWakeup holds completion only while its wake turn reschedules (rescheduled=$rescheduled, fired after $firedAfter)", + ({ rescheduled, firedAfter }) => Effect.gen(function* () { const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const approvalPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: "/workspace", - }); - const firstAttempt = RunAttemptId.make("attempt-claude-wake-approval-1"); - const userAttempt = RunAttemptId.make("attempt-claude-wake-approval-2"); - const bashToolUseId = "toolu_01WakeApprovalBash"; - const stamp = (frame: SDKMessage, promptIndex: number) => - claudeSdkFrame({ - ...frame, - user_message_uuid: harness.promptUuid(promptIndex), - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: firstAttempt, - text: "First.", - attachments: [], - runtimePolicy: approvalPolicy, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000780", text: "One." }), - 0, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000781", result: "One." }), - 0, - ), + yield* startScheduleWakeupTurn(harness); + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); + assert.isTrue( + yield* harness.hasPendingBackgroundWork, + "a wakeup past the idle timeout must keep the session from being released", ); - yield* harness.awaitTerminal(1); + yield* TestClock.adjust(firedAfter); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.awaitContinuation(1); + const now = yield* DateTime.now; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: userAttempt, - text: "Second.", + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-2"), + text: "say WOKE", attachments: [], providerTurnOrdinal: 2, - runtimePolicy: approvalPolicy, + messageCreatedBy: "agent", + messageCreationSource: "provider", }), ); + if (rescheduled) { + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_2", + uuids: ["00000000-0000-4000-8000-000000002201", "00000000-0000-4000-8000-000000002202"], + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "loop", noop: false }, + scheduledFor: DateTime.toEpochMillis(now) + 60_000, + })) { + yield* harness.offerAndWait(frame); + } + } yield* harness.offerAndWait( - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_wake_bash", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: bashToolUseId, - name: "Bash", - input: { command: "git status" }, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000782", - session_id: WAKE_NATIVE_SESSION, - }), - ); - const permission = yield* Effect.promise(() => - harness.getOpenedOptions()!.canUseTool!( - "Bash", - { command: "git status" }, - { - signal: new AbortController().signal, - toolUseID: bashToolUseId, - requestId: "request-wake-bash", - }, - ), - ).pipe(Effect.forkScoped); - - yield* harness.until(() => - harness.events.some((event) => event.type === "runtime_request.updated"), - ); - const request = harness.events.findLast( - (event) => event.type === "runtime_request.updated", + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002203", text: "WOKE" }), ); - const bashItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === bashToolUseId - ? [event.turnItem.runId] - : [], + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002204", result: "WOKE" }), ); - assert.isNotEmpty(bashItems); - assert.isTrue(bashItems.every((runId) => runId === RunId.make(`run-${userAttempt}`))); - if (request?.type !== "runtime_request.updated") return; - yield* harness.runtime.respondToRuntimeRequest({ - requestId: request.runtimeRequest.id, - decision: "accept", - }); - const result = yield* Fiber.join(permission); - assert.equal(result?.behavior, "allow"); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.equal(backgroundWorkHoldsCompletion(publishedRoster(harness)), rescheduled); + assert.equal(yield* harness.hasPendingBackgroundWork, rescheduled); }).pipe( Effect.provide( Layer.mergeAll( @@ -13645,171 +11727,197 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("a user turn before the wakeup fires keeps the pending wakeup's hold", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* startScheduleWakeupTurn(harness); + yield* TestClock.adjust("10 seconds"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-user"), + text: "What time is it?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002401", text: "Noon." }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002402", result: "Noon." }), + ); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect.each([ - { card: "an approval", toolName: "Bash", toolInput: { command: "echo probe" } }, - { - card: "a question", - toolName: "AskUserQuestion", - toolInput: { - questions: [ - { - header: "Target", - question: "Where should this deploy?", - options: [ - { label: "Production", description: "Deploy to production." }, - { label: "Staging", description: "Deploy to staging." }, - ], - multiSelect: false, - }, - ], - }, - }, - ])("closes $card card when Claude withdraws its request", ({ toolName, toolInput }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-withdrawn-approval"), - text: "Run the probe.", - attachments: [], - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: "/workspace", - }), - }), - ); - // The CLI cancels a request once a PermissionRequest hook has answered it. - // @effect-diagnostics-next-line abortControllerInEffect:off - Claude, not the test fiber, withdraws the request. - const withdrawal = new AbortController(); - const permission = yield* Effect.promise(() => - harness.getOpenedOptions()!.canUseTool!(toolName, toolInput, { - signal: withdrawal.signal, - toolUseID: "toolu_01WithdrawnApproval", - requestId: "request-withdrawn-approval", - }), - ).pipe(Effect.forkScoped); - const pending = (yield* Queue.take(harness.runtimeRequestReceipts)).runtimeRequest; - assert.equal(pending.status, "pending"); + it.effect("a task notification waking Claude just before the wakeup keeps its hold", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task"), + text: "Run the build in the background and check back in two minutes.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_fallback", + uuids: ["00000000-0000-4000-8000-000000002501", "00000000-0000-4000-8000-000000002502"], + toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" }, + scheduledFor: DateTime.toEpochMillis(now) + 120_000, + })) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); - // The turn can end right after the withdrawal, before the callback returns. - withdrawal.abort(); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000790", result: "Done." }), - user_message_uuid: harness.promptUuid(0), - }), - ); - yield* harness.awaitTerminal(1); - assert.equal((yield* Fiber.join(permission))?.behavior, "deny"); - // The cancellation has to land before the turn's end finalizes the run. - const beforeTerminal = harness.events.slice( - 0, - harness.events.findIndex((event) => event.type === "turn.terminal"), - ); - const statusOf = (type: "runtime_request.updated" | "node.updated" | "turn_item.updated") => - beforeTerminal - .flatMap((event): Array<{ readonly type: string; readonly status: string }> => - event.type === "runtime_request.updated" && event.runtimeRequest.id === pending.id - ? [{ type: event.type, status: event.runtimeRequest.status }] - : event.type === "node.updated" && event.node.id === pending.nodeId - ? [{ type: event.type, status: event.node.status }] - : event.type === "turn_item.updated" && event.turnItem.nodeId === pending.nodeId - ? [{ type: event.type, status: event.turnItem.status }] - : [], - ) - .findLast((entry) => entry.type === type)?.status; - assert.equal(statusOf("runtime_request.updated"), "cancelled"); - assert.equal(statusOf("node.updated"), "cancelled"); - assert.equal(statusOf("turn_item.updated"), "cancelled"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* TestClock.adjust("60 seconds"); + // Claude runs an empty turn for the notification and opens the real one right after, + // both before the wake run attaches. + yield* harness.offerAndWait(wakeNotification); + yield* Queue.offer(harness.sdkMessages, wakeTurnInit); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002503", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000002504" }), + ); + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.isTrue( + backgroundWorkHoldsCompletion(publishedRoster(harness)), + "the wakeup is still pending after the task notification's wake turn", + ); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("releases output held for a prompt echo when the stream ends", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => Queue.shutdown(sdkMessages), - }); - const now = yield* DateTime.now; - const firstAttempt = RunAttemptId.make("attempt-claude-echo-1"); - const secondAttempt = RunAttemptId.make("attempt-claude-echo-2"); - const stamp = (frame: SDKMessage, promptIndex: number) => - claudeSdkFrame({ - ...frame, - user_message_uuid: harness.promptUuid(promptIndex), - }); - const assistantTexts = () => - harness.events.flatMap((event) => - event.type === "message.updated" && event.message.role === "assistant" - ? [event.message.text] - : [], - ); - + it.effect.each([{ emptyResult: true }, { emptyResult: false }])( + "an early wakeup after an idle task notification releases its hold (empty result: $emptyResult)", + ({ emptyResult }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: firstAttempt, - text: "First.", + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified"), + text: "Run the build in the background and check back in two minutes.", attachments: [], }), ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000701", text: "One." }), - 0, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000702", result: "One." }), - 0, - ), - ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_notified", + uuids: ["00000000-0000-4000-8000-000000002601", "00000000-0000-4000-8000-000000002602"], + toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" }, + scheduledFor: DateTime.toEpochMillis(now) + 120_000, + })) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.offer(harness.sdkMessages, turnOneResult); yield* harness.awaitTerminal(1); + yield* TestClock.adjust("10 seconds"); + yield* harness.offerAndWait(wakeNotification); + if (emptyResult) { + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002603", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + } + + yield* TestClock.adjust("80 seconds"); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.awaitContinuation(1); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: secondAttempt, - text: "Second.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified-2"), + text: "check the build", attachments: [], providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000002604", + text: "Built.", }), ); yield* harness.offerAndWait( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000703", text: "Two." }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002605", result: "Built." }), ); - assert.deepEqual(assistantTexts(), ["One."]); - - yield* Queue.shutdown(harness.sdkMessages); yield* harness.awaitTerminal(2); - assert.deepEqual(assistantTexts(), ["One.", "Two."]); - assert.equal(harness.terminalEvents()[1]?.status, "failed"); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness))); + assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -13820,42 +11928,220 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("a failed turn on a live Claude process keeps the pending wakeup's hold", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* startScheduleWakeupTurn( + harness, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002103", + result: "API Error: 529 overloaded", + subtype: "error_during_execution", + isError: true, + errors: ["API Error: 529 overloaded"], + terminalReason: "model_error", + }), + ); + assert.equal(harness.terminalEvents()[0]?.status, "failed"); + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness))); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect("fails a prompt Claude completes without starting a turn for it", () => - Effect.scoped( + it.effect("ScheduleWakeup stop:true releases the pending wakeup's hold", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-stop"), + text: "Schedule a wakeup, then cancel it.", + attachments: [], + }), + ); + const frames = [ + ...scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_set", + uuids: ["00000000-0000-4000-8000-000000002301", "00000000-0000-4000-8000-000000002302"], + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false }, + scheduledFor: DateTime.toEpochMillis(now) + 60_000, + }), + ...scheduleWakeupFrames({ + toolUseId: "toolu_schedule_wakeup_stop", + uuids: ["00000000-0000-4000-8000-000000002303", "00000000-0000-4000-8000-000000002304"], + toolInput: { stop: true }, + scheduledFor: 0, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002305", result: "Cancelled." }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + yield* harness.awaitTerminal(1); + assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness))); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("Stop on a thread waiting for a ScheduleWakeup closes Claude and drops the hold", () => + Effect.gen(function* () { + let closes = 0; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + }); + yield* startScheduleWakeupTurn(harness); + const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; + assert.isTrue(backgroundWorkHoldsCompletion(settledThread?.pendingBackgroundTasks ?? [])); + // The wakeup alone must not refuse a model or mode change. + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWorkForThread!(settledThread!)); + + yield* harness.runtime.interruptTurn({ + providerThread: settledThread ?? harness.providerThread, + providerTurnId: harness.terminalEvents()[0]!.providerTurnId, + requestRuntimeRestart: true, + }); + + assert.equal(closes, 1, "the wakeup lives in the CLI process, so Stop must close it"); + yield* harness.until(() => publishedRoster(harness).length === 0); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.skipIf(process.getuid === undefined)( + "tails foreground Bash output under the physical cwd the query launched in", + () => Effect.gen(function* () { - // Claude answers previously recorded prompt uuids with only a completed lifecycle frame. - const harness = yield* makeWakeHarness; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-task-output-cwd-", + }); + const physicalCwd = path.join(root, "real", "project"); + const launchCwd = path.join(root, "link"); + yield* fileSystem.makeDirectory(physicalCwd, { recursive: true }); + yield* fileSystem.symlink(physicalCwd, launchCwd); + // The session opens in /workspace; a relative TMPDIR puts Claude's + // task files under whichever cwd the CLI was launched in. Linux, + // because Claude Code's macOS build ignores TMPDIR. + const harness = yield* makeWakeHarnessWithOptions({ environment: { TMPDIR: "../tmp" } }); const now = yield* DateTime.now; + const toolUseId = "toolu_foreground_bash"; + const taskId = "foreground-bash-task"; + const tasks = path.join( + root, + "real", + "tmp", + `claude-${process.getuid?.()}`, + "project", + WAKE_NATIVE_SESSION, + "tasks", + ); + yield* fileSystem.makeDirectory(tasks, { recursive: true }); + yield* fileSystem.writeFileString(path.join(tasks, `${taskId}.output`), "line 1\n"); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-duplicate-prompt"), - text: "Bump this PR to the latest main.", + attemptId: RunAttemptId.make("attempt-claude-task-output-cwd"), + text: "Run the build.", attachments: [], + runtimePolicy: { ...CLAUDE_TEST_RUNTIME_POLICY, cwd: launchCwd }, }), ); - yield* Queue.offer( - harness.sdkMessages, + assert.equal(harness.getOpenedOptions()?.cwd, launchCwd); + for (const frame of [ claudeSdkFrame({ - type: "command_lifecycle", - command_uuid: harness.promptUuid(0), - state: "completed", - uuid: "00000000-0000-4000-8000-000000000790", + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_foreground_bash", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: toolUseId, + name: "Bash", + input: { command: "vp run build", description: "Build" }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000a01", session_id: WAKE_NATIVE_SESSION, }), - ); + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: toolUseId, + description: "vp run build", + is_backgrounded: false, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000a02", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [{ type: "tool_result", tool_use_id: toolUseId, content: "line 1" }], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000a03", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { stdout: "line 1\n", stderr: "", interrupted: false }, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a04", result: "Built." }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } yield* harness.awaitTerminal(1); - const [terminal] = harness.terminalEvents(); - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.equal(terminal.threadDisposition, "reusable"); - assert.include(terminal.failure.message, "never started a turn"); + + const chunks = harness.events.flatMap((event) => + event.type === "command_output.delta" ? [event.chunk] : [], + ); + assert.deepEqual(chunks, ["line 1\n"]); }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), Effect.provide( Layer.mergeAll( IdAllocator.layer, @@ -13865,424 +12151,853 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("lets the native SDK acknowledge Stop before closing its own query", () => + Effect.gen(function* () { + let closes = 0; + let acknowledge = Effect.void; + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Effect.suspend(() => { + assert.equal(closes, 0); + return acknowledge; + }), + close: (messages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(messages))), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("graceful-stop"), + text: "Work until stopped", + attachments: [], + }), + ); + acknowledge = harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000620", + result: "", + subtype: "error_during_execution", + errors: ["Error: Request was aborted."], + terminalReason: "aborted_streaming", + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + ); + const active = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + if (active?.type !== "provider_turn.updated") + return yield* Effect.die("Missing running native turn"); + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: active.providerTurn.id, + requestRuntimeRestart: true, + }); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.equal(closes, 1); + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("bounds an unacknowledged native Stop and settles its turn once", () => + Effect.gen(function* () { + let closes = 0; + const interruptStarted = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Deferred.succeed(interruptStarted, undefined).pipe(Effect.andThen(Effect.never)), + close: (messages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(messages))), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("unacknowledged-stop"), + text: "Work until stopped", + attachments: [], + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + ); + const active = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + if (active?.type !== "provider_turn.updated") + return yield* Effect.die("Missing running native turn"); + const stop = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: active.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(interruptStarted); + assert.equal(closes, 0); + yield* TestClock.adjust("11 seconds"); + yield* Fiber.join(stop); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.equal(closes, 1); + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it - it.effect.each([ - { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, - { case: "keeps a turn running beside a passive mod pane", focus: false }, - ] as const)("$case", ({ focus }) => - Effect.scoped( - Effect.gen(function* () { - const closed = yield* Deferred.make(); - const harness = yield* makeWakeHarnessWithOptions({ - close: () => Deferred.succeed(closed, undefined), - }); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( + it.effect("preserves settled background work until an explicit stop", () => + Effect.gen(function* () { + let closes = 0; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + }); + const now = yield* DateTime.now; + const attemptId = RunAttemptId.make("attempt-claude-settled-stop"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId, + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; + assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + const replacementAttempt = yield* harness.runtime + .startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, - providerThread: harness.providerThread, + providerThread: { + ...harness.providerThread, + nativeThreadRef: { + ...harness.providerThread.nativeThreadRef!, + nativeId: "replacement-session", + }, + }, now, - attemptId: RunAttemptId.make("attempt-claude-mod-pane-focus"), - text: "Run rm -r build", + attemptId: RunAttemptId.make("attempt-claude-background-replacement"), + text: "Continue in a fresh session.", attachments: [], + providerTurnOrdinal: 2, }), - ); - // Captured from Claude 2.1.303 with the blast-radius mod holding a Bash - // call: the mod waits for keyboard input in its pane and nothing else - // arrives until it gives up. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "ui_panes", - panes: [ - { id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }, - ], - shown_id: "blast-radius", - focused_id: null, - focus_requested_id: focus ? "blast-radius" : null, - uuid: "00000000-0000-4000-8000-000000000795", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "ui_invalidate", - event: "ui.render", - uuid: "00000000-0000-4000-8000-000000000796", - session_id: WAKE_NATIVE_SESSION, - }), - ); - // Frames are handled in order, so a later notice proves the pane frame - // was handled without the turn ending. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "informational", - content: "Processing barrier.", - level: "warning", - uuid: "00000000-0000-4000-8000-000000000797", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.until( - () => - harness.terminalEvents().length > 0 || - harness.events.some( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "system_notice", - ), - ); - const [terminal] = harness.terminalEvents(); - if (!focus) { - assert.equal(terminal, undefined); - return; - } - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.include(terminal.failure.message, "blast-radius"); - // The held tool call is abandoned by closing the query, never answered. - yield* Deferred.await(closed); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + ) + .pipe(Effect.result); + assert.equal(replacementAttempt._tag, "Failure"); + assert.equal(closes, 0); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + yield* harness.runtime.interruptTurn({ + providerThread: settledThread ?? harness.providerThread, + providerTurnId: harness.terminalEvents()[0]!.providerTurnId, + requestRuntimeRestart: true, + }); + + assert.equal(closes, 1, "Stop must close the CLI process that owns the task"); + yield* harness.until( + () => + (providerThreadRosterEvents(harness.events).at(-1)?.providerThread.pendingBackgroundTasks + ?.length ?? 0) === 0, + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.continuationRequests, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - // regression: #17531 a follow-up sent while the failed mod turn's process closes gets a new process - it.effect("runs a follow-up in a fresh query while the mod-blocked query is closing", () => - Effect.scoped( - Effect.gen(function* () { - const releaseClose = yield* Deferred.make(); - const replacementClosedOld = yield* Deferred.make(); - let oldCloses = 0; - const harness = yield* makeWakeHarnessWithOptions({ - // The held CLI never answers an interrupt; closure must not need one. - interrupt: Effect.never, - close: (sdkMessages) => + it.effect.each([ + { teardown: "before Stop" as const }, + { teardown: "during Stop's interrupt write" as const }, + ])("Stop with session teardown $teardown does not fail on the closed CLI", ({ teardown }) => + Effect.gen(function* () { + const sessionScope = yield* Scope.make(); + let queryClosed = false; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Effect.sync(() => { + queryClosed = true; + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + interrupt: Effect.suspend(() => + teardown === "before Stop" ? Effect.void : Scope.close(sessionScope, Exit.void), + ).pipe( + Effect.andThen( Effect.suspend(() => - ++oldCloses === 2 ? Deferred.succeed(replacementClosedOld, undefined) : Effect.void, - ).pipe( - Effect.andThen(Deferred.await(releaseClose)), - Effect.andThen(Queue.shutdown(sdkMessages)), + queryClosed + ? Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "interrupt", + cause: new Error("ProcessTransport is not ready for writing"), + }), + ) + : Effect.void, ), - freshQueueOnReopen: true, - }); - // Added after the harness so it runs first: a failed assertion must not - // leave teardown waiting on the held close. - yield* Effect.addFinalizer(() => Deferred.succeed(releaseClose, undefined)); - const now = yield* DateTime.now; - const turnInput = makeClaudeTestTurnInput({ + ), + ), + }).pipe(Scope.provide(sessionScope)); + const now = yield* DateTime.now; + const attemptId = RunAttemptId.make("attempt-claude-closed-scope-stop"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-mod-pane-blocked"), - text: "Run rm -r build", + attemptId, + text: "Hand this thread off to a worktree.", + attachments: [], + }), + ); + // A workspace handoff detaches the session, closing its scope while the turn streams. + if (teardown === "before Stop") { + yield* Scope.close(sessionScope, Exit.void); + assert.isTrue(queryClosed); + } + + const interrupted = yield* Effect.exit( + harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + requestRuntimeRestart: true, + }), + ); + + assert.isTrue(Exit.isSuccess(interrupted), String(interrupted)); + assert.isTrue(queryClosed); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("a settled Stop leaves a turn that replaced the closing process alone", () => + Effect.gen(function* () { + const changes = yield* makeChangeSignal; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-settled-stop-replaced-", + }); + const processQueues: Array> = []; + const firstCloseRequested = yield* Deferred.make(); + const events: Array = []; + const continuationRequests: Array = + []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }).pipe(Effect.andThen(changes.notify)), + }, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + const isFirstProcess = processQueues.length === 0; + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: isFirstProcess + ? Deferred.succeed(firstCloseRequested, undefined).pipe(Effect.asVoid) + : Queue.shutdown(sdkMessages), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-settled-stop-replaced"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-settled-stop"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const terminals = () => events.filter((event) => event.type === "turn.terminal"); + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-a"), + text: "Run the build in the background.", attachments: [], - }); - yield* harness.runtime.startTurn(turnInput); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "ui_panes", - panes: [ - { id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }, - ], - shown_id: "blast-radius", - focused_id: null, - focus_requested_id: "blast-radius", - uuid: "00000000-0000-4000-8000-000000000798", - session_id: WAKE_NATIVE_SESSION, - }), - ); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); + }), + ); + yield* Queue.offer(processQueues[0]!, wakeTaskStarted); + yield* Queue.offer(processQueues[0]!, turnOneResult); + yield* changes.until(() => terminals().length === 1); + const settledThread = providerThreadRosterEvents(events).at(-1)?.providerThread; + const settledTurn = terminals()[0]; + assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); - const followUp = yield* harness.runtime - .startTurn({ - ...turnInput, - attemptId: RunAttemptId.make("attempt-claude-after-mod-pane"), - providerTurnOrdinal: 2, - }) - .pipe(Effect.forkScoped); - // Reusing the closing process would offer the prompt to it instead. - yield* Effect.raceFirst( - Deferred.await(replacementClosedOld), - harness.until(() => harness.offeredMessages.length >= 2), - ); - assert.isTrue(yield* Deferred.isDone(replacementClosedOld)); - yield* Deferred.succeed(releaseClose, undefined); - yield* Fiber.join(followUp); - assert.equal(harness.processQueues.length, 2); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "after-mod-pane-result", result: "Done." }), - ); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); + const stop = yield* runtime + .interruptTurn({ + providerThread: settledThread ?? providerThread, + providerTurnId: settledTurn!.providerTurnId, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(firstCloseRequested); - // regression: #16897 a prompt whose uuid the session already holds must not hang or end early - it.effect("keeps a started prompt running until its result", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-started-prompt"), - text: "Bump this PR to the latest main.", - attachments: [], - }), - ); - const lifecycle = (state: string, uuid: string) => - claudeSdkFrame({ - type: "command_lifecycle", - command_uuid: harness.promptUuid(0), - state, - uuid, - session_id: WAKE_NATIVE_SESSION, - }); - yield* Queue.offer( - harness.sdkMessages, - lifecycle("queued", "00000000-0000-4000-8000-000000000791"), - ); - yield* Queue.offer( - harness.sdkMessages, - lifecycle("started", "00000000-0000-4000-8000-000000000792"), - ); - // The CLI can report the prompt completed before its turn's result. - yield* Queue.offer( - harness.sdkMessages, - lifecycle("completed", "00000000-0000-4000-8000-000000000793"), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000794", result: "Done." }), - user_message_uuid: harness.promptUuid(0), - }), - ); - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-b"), + text: "Start another background build.", + attachments: [], + providerTurnOrdinal: 2, + modelSelection: { + ...CLAUDE_TEST_MODEL_SELECTION, + model: "claude-haiku-4-5-20251001", + }, + }), + ); + assert.lengthOf(processQueues, 2); + const replacementTaskId = "replacement-task"; + yield* Queue.offer( + processQueues[1]!, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: replacementTaskId, + uuid: "00000000-0000-4000-8000-000000000905", + }), + ); + yield* changes.until( + () => + providerThreadRosterEvents(events).at(-1)?.providerThread.pendingBackgroundTasks?.[0] + ?.taskId === replacementTaskId, + ); + + yield* Queue.shutdown(processQueues[0]!); + yield* Fiber.join(stop); + assert.isTrue(yield* hasPendingBackgroundWork); + yield* yieldTicks(50); + const latestThread = providerThreadRosterEvents(events).at(-1)?.providerThread; + assert.equal(latestThread?.status, "active"); + assert.deepEqual( + latestThread?.pendingBackgroundTasks?.map((task) => task.taskId), + [replacementTaskId], + ); + + yield* Queue.offer( + processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000906", + result: "Started another build.", + }), + ); + yield* changes.until(() => terminals().length === 2); + yield* Queue.offer( + processQueues[1]!, + claudeSdkFrame({ + ...wakeNotification, + task_id: replacementTaskId, + uuid: "00000000-0000-4000-8000-000000000907", + }), + ); + yield* Queue.offer( + processQueues[1]!, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000908", + text: WAKE_ASSISTANT_TEXT, + }), + ); + yield* changes.until(() => continuationRequests.length === 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("buffers wake output and requests a single continuation run", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-1"), - text: "Run the build in the background.", - attachments: [], + const openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame = Effect.fnUntraced(function* ( + name: string, + ) { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: `t3-claude-v2-${name}-`, + }); + const deadStreamEnded = yield* Deferred.make(); + let opened = 0; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + // startTurn reads the auto-compact window from settings between opening the query and + // attaching the turn; holding that read until the CLI's stream has ended pins the race. + fileSystem: { + ...fileSystem, + readFileString: (filePath, encoding) => + opened === 1 && filePath.endsWith("settings.json") + ? Deferred.await(deadStreamEnded).pipe( + Effect.andThen(fileSystem.readFileString(filePath, encoding)), + ) + : fileSystem.readFileString(filePath, encoding), + }, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + continuationRequests: { offer: () => Effect.void }, + queryRunner: { + allocateSessionId: Effect.succeed(`native-${name}`), + open: () => + Effect.gen(function* () { + opened += 1; + const sdkMessages = yield* Queue.unbounded(); + return { + // The first CLI exits without writing a frame. + messages: + opened === 1 + ? Stream.empty.pipe(Stream.ensuring(Deferred.succeed(deadStreamEnded, undefined))) + : Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); - - yield* harness.offerAndWait(wakeNotification); - assert.lengthOf(harness.continuationRequests, 0); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - yield* Queue.offer(harness.sdkMessages, wakeAssistant); - yield* harness.awaitContinuation(1); - assert.equal(harness.continuationRequests[0]?.threadId, harness.threadId); - assert.equal(harness.continuationRequests[0]?.providerThreadId, harness.providerThread.id); - assert.equal(harness.continuationRequests[0]?.driver, ClaudeAdapterV2.CLAUDE_PROVIDER); - assert.equal(harness.continuationRequests[0]?.detail, WAKE_SUMMARY); + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make(`thread-${name}`); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`provider-session-${name}`), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const now = yield* DateTime.now; + const turnInput = (attempt: string, providerTurnOrdinal: number) => + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make(`attempt-${name}-${attempt}`), + text: "Continue with the plan.", + attachments: [], + providerTurnOrdinal, + }); + return { runtime, turnInput }; + }); - yield* harness.offerAndWait(wakeResult); - assert.lengthOf(harness.continuationRequests, 1); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + it.effect("fails a turn whose Claude query ends before its first frame", () => + Effect.gen(function* () { + const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame( + "claude-query-dies-before-frame", + ); + const started = yield* harness.runtime.startTurn(harness.turnInput("a", 1)).pipe(Effect.exit); + assert.isTrue( + Exit.isFailure(started), + "a turn whose Claude query ended before its first frame started running on the dead query", + ); + if (Exit.isFailure(started)) { + assert.include( + Cause.pretty(started.cause), + "Claude provider query ended before the turn could start.", + ); + } + const followUp = yield* harness.runtime + .startTurn(harness.turnInput("b", 2)) + .pipe(Effect.exit); + assert.isTrue( + Exit.isSuccess(followUp), + `the turn whose query ended before its first frame is still active: ${ + Exit.isFailure(followUp) ? Cause.pretty(followUp.cause) : "" + }`, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("starts the wake run when Claude opens the wake turn, before its output", () => - Effect.scoped( + it.effect( + "clears the replaced sibling native thread roster when openQuery switches processes", + () => Effect.gen(function* () { - const harness = yield* makeWakeHarness; + const changes = yield* makeChangeSignal; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-sibling-replace-", + }); + const nativeIds = ["native-thread-roster-a", "native-thread-roster-b"] as const; + let allocateIndex = 0; + // A shared queue would hide sibling process death on replacement. + const processQueues: Array<{ + readonly nativeThreadId: string; + readonly queue: Queue.Queue; + }> = []; + const events: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + continuationRequests: { + offer: () => Effect.void, + }, + queryRunner: { + allocateSessionId: Effect.sync(() => { + const next = + nativeIds[allocateIndex] ?? `native-thread-roster-extra-${allocateIndex}`; + allocateIndex += 1; + return next; + }), + open: (openInput) => + Effect.gen(function* () { + const nativeThreadId = openInput.options.sessionId ?? openInput.options.resume; + if (typeof nativeThreadId !== "string" || nativeThreadId.length === 0) { + return yield* Effect.die("openQuery must supply a native session id"); + } + const queue = yield* Queue.unbounded(); + processQueues.push({ nativeThreadId, queue }); + return { + messages: Stream.fromQueue(queue), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(queue), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const appThreadA = ThreadId.make("thread-claude-roster-a"); + const appThreadB = ThreadId.make("thread-claude-roster-b"); + const runtime = yield* adapter.openSession({ + threadId: appThreadA, + providerSessionId: ProviderSessionId.make("provider-session-claude-sibling-replace"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThreadA = yield* runtime.ensureThread({ + threadId: appThreadA, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThreadB = yield* runtime.ensureThread({ + threadId: appThreadB, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + assert.notEqual( + providerThreadA.nativeThreadRef?.nativeId, + providerThreadB.nativeThreadRef?.nativeId, + ); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); + } + if (runtime.hasPendingBackgroundWorkForThread === undefined) { + return yield* Effect.die( + "Claude adapter runtime must expose hasPendingBackgroundWorkForThread.", + ); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const hasPendingBackgroundWorkForThread = runtime.hasPendingBackgroundWorkForThread; const now = yield* DateTime.now; + const taskA = "task-roster-a"; + const taskB = "task-roster-b"; - yield* harness.runtime.startTurn( + yield* runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, + threadId: appThreadA, + providerThread: providerThreadA, now, - attemptId: RunAttemptId.make("attempt-claude-wake-init-1"), - text: "Run the build in the background.", + attemptId: RunAttemptId.make("attempt-roster-iso-a"), + text: "Background work on A.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - - yield* harness.offerAndWait(wakeNotification); - assert.lengthOf(harness.continuationRequests, 0); - yield* harness.offerAndWait(wakeTurnInit); - assert.lengthOf(harness.continuationRequests, 1); - assert.equal(harness.continuationRequests[0]?.detail, WAKE_SUMMARY); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-init-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", + assert.equal(processQueues.length, 1); + const processA = processQueues[0]!; + yield* Queue.offer( + processA.queue, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskA, + tool_use_id: "toolu-roster-a", + description: "work on A", + is_backgrounded: true, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000301", + session_id: nativeIds[0], }), ); - assert.lengthOf(harness.terminalEvents(), 1); - - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.lengthOf(harness.continuationRequests, 1); - assert.isTrue( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, - ), + yield* Queue.offer( + processA.queue, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000302", + result: "A settled with background work.", + }), ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + yield* changes.until(() => + events.some( + (event) => + event.type === "turn.terminal" && + event.providerThreadId === providerThreadA.id && + event.status === "completed", ), - ), - ), - ), - ); - - it.effect("offers a later wake after an earlier wake's continuation dispatch failed", () => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const SECOND_SUMMARY = 'Background command "Second sleep" completed (exit code 0)'; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + ); + const rosterAAfterSettle = providerThreadRosterEvents(events).findLast( + (event) => event.providerThread.id === providerThreadA.id, + )?.providerThread.pendingBackgroundTasks; + assert.deepEqual(rosterAAfterSettle ?? [], [ + { + taskId: taskA, + description: "work on A", + kind: "command", + nativeItemId: "toolu-roster-a", + }, + ]); + assert.isTrue(yield* hasPendingBackgroundWork); + assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadA)); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - yield* harness.runtime.startTurn( + yield* runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, + threadId: appThreadB, + providerThread: { ...providerThreadB, status: "active" }, now, - attemptId: RunAttemptId.make("attempt-claude-wake-dispatch-failed-1"), - text: "Run two builds in the background.", + attemptId: RunAttemptId.make("attempt-roster-iso-b"), + text: "Background work on B.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + assert.equal(processQueues.length, 2); + yield* changes.until(() => + providerThreadRosterEvents(events).some( + (event) => + event.providerThread.id === providerThreadA.id && + event.providerThread.status === "idle" && + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ), + ); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); + + const processB = processQueues[1]!; yield* Queue.offer( - harness.sdkMessages, + processB.queue, claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - description: "Second sleep", - uuid: "00000000-0000-4000-8000-000000000121", + type: "system", + subtype: "task_started", + task_id: taskB, + tool_use_id: "toolu-roster-b", + description: "work on B", + is_backgrounded: true, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000303", + session_id: nativeIds[1], }), ); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - - // A failed dispatch never attaches the wake turn; clearIfCurrent is the only release. - const failed = harness.continuationRequests[0]!; - assert.isDefined(failed.clearIfCurrent); - yield* failed.clearIfCurrent!(); - yield* harness.until( - () => - !( - providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks ?? [] - ).some((task) => task.taskId === WAKE_TASK_ID), + yield* changes.until(() => + providerThreadRosterEvents(events).some( + (event) => + event.providerThread.id === providerThreadB.id && + (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ), ); + assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadB)); + assert.isTrue(yield* hasPendingBackgroundWork); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - yield* harness.offerAndWait( + yield* Queue.offer( + processB.queue, claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - summary: SECOND_SUMMARY, - uuid: "00000000-0000-4000-8000-000000000123", + type: "result", + subtype: "error_during_execution", + duration_ms: 10, + duration_api_ms: 10, + is_error: true, + num_turns: 1, + result: "B failed", + stop_reason: "end_turn", + total_cost_usd: 0, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + modelUsage: {}, + permission_denials: [], + errors: ["B failed"], + terminal_reason: "model_error", + uuid: "00000000-0000-4000-8000-000000000304", + session_id: nativeIds[1], }), ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000124" }), + yield* changes.until(() => + events.some( + (event) => + event.type === "turn.terminal" && + event.providerThreadId === providerThreadB.id && + event.status === "failed", + ), ); - assert.lengthOf(harness.continuationRequests, 2); + + const rosterBAfterFail = providerThreadRosterEvents(events).findLast( + (event) => event.providerThread.id === providerThreadB.id, + )?.providerThread.pendingBackgroundTasks; + assert.deepEqual(rosterBAfterFail ?? [], []); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); + assert.isFalse(yield* hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -14293,112 +13008,199 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect("keeps a newer wake's output when a stale continuation request is cleared", () => - Effect.scoped( + it.effect.each(["full-access", "approval-required"] as const)( + "keeps a queued wake turn's tool callback with its continuation in %s mode", + (runtimeMode) => Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; const harness = yield* makeWakeHarness; const now = yield* DateTime.now; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "default", + cwd: "/workspace", + }); + const firstAttempt = RunAttemptId.make("attempt-claude-wake-callback-1"); + const userAttempt = RunAttemptId.make("attempt-claude-wake-callback-2"); + const continuationAttempt = RunAttemptId.make("attempt-claude-wake-callback-3"); + const planToolUseId = "toolu_01WakePlanExitPlanMode"; + const planMarkdown = "# Wake plan\n\n1. Report the background result."; + const stamp = (frame: SDKMessage, promptIndex: number) => + claudeSdkFrame({ + ...frame, + user_message_uuid: harness.promptUuid(promptIndex), + }); + const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`); + const planToolUse = claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_wake_plan", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: planToolUseId, + name: "ExitPlanMode", + input: { plan: planMarkdown }, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000741", + session_id: WAKE_NATIVE_SESSION, + }); + const planToolResult = claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: planToolUseId, + content: + "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", + is_error: true, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000742", + session_id: WAKE_NATIVE_SESSION, + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-1"), - text: "Run two builds in the background.", + attemptId: firstAttempt, + text: "Run the build in the background.", attachments: [], + runtimePolicy, }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0)); yield* Queue.offer( harness.sdkMessages, - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - description: "Second sleep", - uuid: "00000000-0000-4000-8000-000000000131", - }), + stamp( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000740", result: "STARTED" }), + 0, + ), ); - yield* Queue.offer(harness.sdkMessages, turnOneResult); yield* harness.awaitTerminal(1); - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - assert.lengthOf(harness.continuationRequests, 1); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-2"), - text: "Background task completed.", + attemptId: userAttempt, + text: "Reply with exactly: USER_REPLY", attachments: [], + runtimePolicy, providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", }), ); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.awaitTerminal(2); - - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - uuid: "00000000-0000-4000-8000-000000000133", - }), + yield* Queue.offer(harness.sdkMessages, wakeNotification); + // The SDK asks for permission only after streaming the tool_use. + yield* harness.offerAndWait(planToolUse); + const canUseTool = harness.getOpenedOptions()?.canUseTool; + assert.isFunction(canUseTool); + const callback = yield* Effect.promise(() => + canUseTool!( + "ExitPlanMode", + { plan: planMarkdown }, + { + signal: new AbortController().signal, + toolUseID: planToolUseId, + requestId: "request-wake-plan", + }, + ), ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000134" }), + assert.equal(callback?.behavior, "deny"); + assert.include( + callback?.behavior === "deny" ? callback.message : "", + "The client captured your proposed plan", ); - assert.lengthOf(harness.continuationRequests, 2); + yield* Queue.offer(harness.sdkMessages, planToolResult); + yield* Queue.offer(harness.sdkMessages, wakeResult); + yield* harness.awaitContinuation(1); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* harness.offerAndWait( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000135", - text: "Second build done.", - }), + yield* Queue.offer( + harness.sdkMessages, + stamp( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000743", + text: "USER_REPLY", + }), + 1, + ), ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000136", - result: "Second build done.", - origin: { kind: "task-notification" }, - }), + yield* Queue.offer( + harness.sdkMessages, + stamp( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000744", + result: "USER_REPLY", + }), + 1, + ), ); - assert.lengthOf(harness.continuationRequests, 2); + yield* harness.awaitTerminal(2); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-3"), + attemptId: continuationAttempt, text: "Background task completed.", attachments: [], + runtimePolicy, providerTurnOrdinal: 3, messageCreatedBy: "agent", messageCreationSource: "provider", }), ); yield* harness.awaitTerminal(3); - assert.isTrue( - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text === "Second build done.", + + const latestItems = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" ? [[String(event.turnItem.id), event.turnItem]] : [], ), - "clearing the first wake's request must not discard the second wake's output", + ); + const planTool = [...latestItems.values()].find( + (item) => item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === planToolUseId, + ); + const proposedPlans = [...latestItems.values()].filter( + (item) => item.type === "proposed_plan", + ); + const plans = harness.events.flatMap((event) => + event.type === "plan.updated" && event.plan.kind === "proposed_plan" ? [event.plan] : [], + ); + const planToolRuns = harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === planToolUseId && + event.turnItem.type === "dynamic_tool" + ? [event.turnItem.runId] + : [], + ); + assert.isNotEmpty(planToolRuns); + assert.isTrue(planToolRuns.every((runId) => runId === runOf(continuationAttempt))); + assert.equal(planTool?.runId, runOf(continuationAttempt)); + assert.lengthOf(proposedPlans, 1); + assert.equal(proposedPlans[0]?.runId, runOf(continuationAttempt)); + assert.isTrue(plans.length > 0); + assert.isTrue(plans.every((plan) => plan.runId === runOf(continuationAttempt))); + const userRunItems = [...latestItems.values()].filter( + (item) => item.runId === runOf(userAttempt), + ); + assert.deepEqual( + userRunItems.map((item) => item.type), + ["assistant_message"], ); }).pipe( Effect.provide( @@ -14410,955 +13212,1302 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("stores a Bash result's stdout and stderr as command output", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const attemptId = RunAttemptId.make("attempt-claude-bash-output"); + const bashToolUseId = "toolu_01BashOutput"; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId, + text: "Run it.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_bash_output", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: bashToolUseId, + name: "Bash", + input: { command: "git status" }, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000790", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { type: "tool_result", tool_use_id: bashToolUseId, content: "On branch main" }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000791", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { + stdout: "On branch main", + stderr: "warning: dirty", + interrupted: false, + isImage: false, + }, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000792", result: "Done." }), + ); + yield* harness.awaitTerminal(1); + + const bash = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === bashToolUseId, + ); + assert.equal( + bash?.type === "turn_item.updated" && bash.turnItem.type === "command_execution" + ? bash.turnItem.output + : undefined, + "On branch main\nwarning: dirty", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each([ + { + case: "an Edit", + toolName: "Edit", + toolInput: { + file_path: "/workspace/src/math.ts", + old_string: " return a - b;", + new_string: " return a + b;", + }, + toolUseResult: { + filePath: "/workspace/src/math.ts", + oldString: " return a - b;", + newString: " return a + b;", + originalFile: "export function add(a: number, b: number) {\n return a - b;\n}\n", + structuredPatch: [ + { + oldStart: 1, + oldLines: 3, + newStart: 1, + newLines: 3, + lines: [ + " export function add(a: number, b: number) {", + "- return a - b;", + "+ return a + b;", + " }", + ], + }, + ], + userModified: false, + replaceAll: false, + }, + diffStr: + "--- /workspace/src/math.ts\n+++ /workspace/src/math.ts\n@@ -1,3 +1,3 @@\n export function add(a: number, b: number) {\n- return a - b;\n+ return a + b;\n }\n", + }, + { + case: "a Write that creates a file", + toolName: "Write", + toolInput: { file_path: "/workspace/notes.md", content: "# Notes\n\nShip it.\n" }, + toolUseResult: { + type: "create", + filePath: "/workspace/notes.md", + content: "# Notes\n\nShip it.\n", + structuredPatch: [], + originalFile: null, + userModified: false, + }, + diffStr: "--- /dev/null\n+++ /workspace/notes.md\n@@ -0,0 +1,3 @@\n+# Notes\n+\n+Ship it.\n", + }, + { + case: "a Write that creates an empty file", + toolName: "Write", + toolInput: { file_path: "/workspace/.keep", content: "" }, + toolUseResult: { + type: "create", + filePath: "/workspace/.keep", + content: "", + structuredPatch: [], + originalFile: null, + userModified: false, + }, + diffStr: undefined, + }, + ])("stores the diff panel patch for $case", (testCase) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const toolUseId = `toolu_01${testCase.toolName}Patch`; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-claude-${testCase.toolName}-patch`), + text: "Change it.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: `msg_${testCase.toolName}_patch`, + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: toolUseId, + name: testCase.toolName, + input: testCase.toolInput, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000793", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: toolUseId, + content: `The file ${testCase.toolInput.file_path} has been updated successfully.`, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000794", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: testCase.toolUseResult, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000795", result: "Done." }), + ); + yield* harness.awaitTerminal(1); + + const fileChange = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === toolUseId, + ); + assert.deepEqual( + fileChange?.type === "turn_item.updated" && fileChange.turnItem.type === "file_change" + ? { diffStr: fileChange.turnItem.diffStr } + : undefined, + { diffStr: testCase.diffStr }, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect("offers the next wake when a cancelled wake's release arrives after it opened", () => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + it.effect("answers an approval a held wake turn raises without waiting for the echo", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const approvalPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: "/workspace", + }); + const firstAttempt = RunAttemptId.make("attempt-claude-wake-approval-1"); + const userAttempt = RunAttemptId.make("attempt-claude-wake-approval-2"); + const bashToolUseId = "toolu_01WakeApprovalBash"; + const stamp = (frame: SDKMessage, promptIndex: number) => + claudeSdkFrame({ + ...frame, + user_message_uuid: harness.promptUuid(promptIndex), + }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-late-release"), - text: "Run two builds in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000141", - }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: firstAttempt, + text: "First.", + attachments: [], + runtimePolicy: approvalPolicy, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + stamp( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000780", text: "One." }), + 0, + ), + ); + yield* Queue.offer( + harness.sdkMessages, + stamp(makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000781", result: "One." }), 0), + ); + yield* harness.awaitTerminal(1); - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000142", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000143" }), - ); - assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: userAttempt, + text: "Second.", + attachments: [], + providerTurnOrdinal: 2, + runtimePolicy: approvalPolicy, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_wake_bash", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: bashToolUseId, + name: "Bash", + input: { command: "git status" }, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000782", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const permission = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Bash", + { command: "git status" }, + { + signal: new AbortController().signal, + toolUseID: bashToolUseId, + requestId: "request-wake-bash", + }, + ), + ).pipe(Effect.forkScoped); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000144" }), - ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000145", result: "Done." }), - ); - assert.lengthOf( - harness.continuationRequests, - 2, - "the wake that opened before the cancelled wake's release must get its own continuation", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.until(() => + harness.events.some((event) => event.type === "runtime_request.updated"), + ); + const request = harness.events.findLast((event) => event.type === "runtime_request.updated"); + const bashItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === bashToolUseId + ? [event.turnItem.runId] + : [], + ); + assert.isNotEmpty(bashItems); + assert.isTrue(bashItems.every((runId) => runId === RunId.make(`run-${userAttempt}`))); + if (request?.type !== "runtime_request.updated") return; + yield* harness.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + decision: "accept", + }); + const result = yield* Fiber.join(permission); + assert.equal(result?.behavior, "allow"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("does not offer a wake again when it is cancelled before its first root frame", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-early-cancel"), - text: "Start an agent in the background.", - attachments: [], + it.effect.each([ + { card: "an approval", toolName: "Bash", toolInput: { command: "echo probe" } }, + { + card: "a question", + toolName: "AskUserQuestion", + toolInput: { + questions: [ + { + header: "Target", + question: "Where should this deploy?", + options: [ + { label: "Production", description: "Deploy to production." }, + { label: "Staging", description: "Deploy to staging." }, + ], + multiSelect: false, + }, + ], + }, + }, + ])("closes $card card when Claude withdraws its request", ({ toolName, toolInput }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-withdrawn-approval"), + text: "Run the probe.", + attachments: [], + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: "/workspace", }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); + }), + ); + // The CLI cancels a request once a PermissionRequest hook has answered it. + // @effect-diagnostics-next-line abortControllerInEffect:off - Claude, not the test fiber, withdraws the request. + const withdrawal = new AbortController(); + const permission = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!(toolName, toolInput, { + signal: withdrawal.signal, + toolUseID: "toolu_01WithdrawnApproval", + requestId: "request-withdrawn-approval", + }), + ).pipe(Effect.forkScoped); + const pending = (yield* Queue.take(harness.runtimeRequestReceipts)).runtimeRequest; + assert.equal(pending.status, "pending"); - yield* harness.offerAndWait(wakeNotification); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - assert.lengthOf( - harness.continuationRequests, - 1, - "the cancelled wake must not be offered again", + // The turn can end right after the withdrawal, before the callback returns. + withdrawal.abort(); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000790", result: "Done." }), + user_message_uuid: harness.promptUuid(0), + }), + ); + yield* harness.awaitTerminal(1); + assert.equal((yield* Fiber.join(permission))?.behavior, "deny"); + // The cancellation has to land before the turn's end finalizes the run. + const beforeTerminal = harness.events.slice( + 0, + harness.events.findIndex((event) => event.type === "turn.terminal"), + ); + const statusOf = (type: "runtime_request.updated" | "node.updated" | "turn_item.updated") => + beforeTerminal + .flatMap((event): Array<{ readonly type: string; readonly status: string }> => + event.type === "runtime_request.updated" && event.runtimeRequest.id === pending.id + ? [{ type: event.type, status: event.runtimeRequest.status }] + : event.type === "node.updated" && event.node.id === pending.nodeId + ? [{ type: event.type, status: event.node.status }] + : event.type === "turn_item.updated" && event.turnItem.nodeId === pending.nodeId + ? [{ type: event.type, status: event.turnItem.status }] + : [], + ) + .findLast((entry) => entry.type === type)?.status; + assert.equal(statusOf("runtime_request.updated"), "cancelled"); + assert.equal(statusOf("node.updated"), "cancelled"); + assert.equal(statusOf("turn_item.updated"), "cancelled"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("releases output held for a prompt echo when the stream ends", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + }); + const now = yield* DateTime.now; + const firstAttempt = RunAttemptId.make("attempt-claude-echo-1"); + const secondAttempt = RunAttemptId.make("attempt-claude-echo-2"); + const stamp = (frame: SDKMessage, promptIndex: number) => + claudeSdkFrame({ + ...frame, + user_message_uuid: harness.promptUuid(promptIndex), + }); + const assistantTexts = () => + harness.events.flatMap((event) => + event.type === "message.updated" && event.message.role === "assistant" + ? [event.message.text] + : [], ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000146" }), - ); - assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: firstAttempt, + text: "First.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + stamp( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000701", text: "One." }), + 0, + ), + ); + yield* Queue.offer( + harness.sdkMessages, + stamp(makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000702", result: "One." }), 0), + ); + yield* harness.awaitTerminal(1); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: secondAttempt, + text: "Second.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000703", text: "Two." }), + ); + assert.deepEqual(assistantTexts(), ["One."]); + + yield* Queue.shutdown(harness.sdkMessages); + yield* harness.awaitTerminal(2); + assert.deepEqual(assistantTexts(), ["One.", "Two."]); + assert.equal(harness.terminalEvents()[1]?.status, "failed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("offers a later task's wake when a cancelled wake never opens", () => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-never-opens"), - text: "Start an agent and a build in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000151", - }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); - - // Claude never opens a wake for the agent's notification. - yield* harness.offerAndWait(wakeNotification); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - uuid: "00000000-0000-4000-8000-000000000152", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000153" }), - ); - yield* harness.offerAndWait( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000154", text: "Built." }), - ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000155", result: "Built." }), - ); - assert.lengthOf( - harness.continuationRequests, - 2, - "the build's wake must get its own continuation", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + it.effect("fails a prompt Claude completes without starting a turn for it", () => + Effect.gen(function* () { + // Claude answers previously recorded prompt uuids with only a completed lifecycle frame. + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-duplicate-prompt"), + text: "Bump this PR to the latest main.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state: "completed", + uuid: "00000000-0000-4000-8000-000000000790", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.awaitTerminal(1); + const [terminal] = harness.terminalEvents(); + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.threadDisposition, "reusable"); + assert.include(terminal.failure.message, "never started a turn"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it it.effect.each([ - { ending: "notification", cancelled: "after its result" }, - { ending: "tool result", cancelled: "after its result" }, - { ending: "tool result", cancelled: "while the subagent ran" }, - ] as const)( - "does not replay a subagent that finished inside a cancelled wake (ended by $ending, cancelled $cancelled)", - ({ ending, cancelled }) => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const SUBAGENT_TASK_ID = "fg-agent"; - const SUBAGENT_TOOL_USE_ID = "toolu-fg-agent"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent"), - text: "Run two builds in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000161", - }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); - - // The first wake runs a subagent to completion before its result. - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - description: "Inspect build output", - subagent_type: "general-purpose", - task_type: "local_agent", - prompt: "Inspect the build output.", - uuid: "00000000-0000-4000-8000-000000000162", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000168", - text: "Reading the build log.", - }), - parent_tool_use_id: SUBAGENT_TOOL_USE_ID, - }), - ); - if (cancelled === "while the subagent ran") { - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - } - yield* harness.offerAndWait( - ending === "notification" - ? claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - status: "completed", - output_file: "/tmp/fg-agent.output", - summary: "Inspected", - uuid: "00000000-0000-4000-8000-000000000163", - session_id: WAKE_NATIVE_SESSION, - }) - : claudeSdkFrame({ - type: "user", - uuid: "00000000-0000-4000-8000-000000000163", - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: SUBAGENT_TOOL_USE_ID, - content: "Inspected", - }, - ], - }, - }), - ); - yield* harness.offerAndWait(wakeResult); - if (cancelled === "after its result") { - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - } - - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - uuid: "00000000-0000-4000-8000-000000000164", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000165" }), - ); - assert.lengthOf(harness.continuationRequests, 2); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.offerAndWait( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000166", - text: "Second build done.", - }), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000167", - result: "Second build done.", - origin: { kind: "task-notification" }, - }), - ); - yield* harness.awaitTerminal(2); - - const subagentStatuses = harness.events.flatMap((event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === SUBAGENT_TASK_ID - ? [event.subagent.status] - : [], - ); - assert.notInclude( - subagentStatuses, - "running", - "a subagent that finished in the cancelled wake must not be replayed as running", - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, + { case: "keeps a turn running beside a passive mod pane", focus: false }, + ] as const)("$case", ({ focus }) => + Effect.gen(function* () { + const closed = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: () => Deferred.succeed(closed, undefined), + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-mod-pane-focus"), + text: "Run rm -r build", + attachments: [], + }), + ); + // Captured from Claude 2.1.303 with the blast-radius mod holding a Bash + // call: the mod waits for keyboard input in its pane and nothing else + // arrives until it gives up. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_panes", + panes: [{ id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }], + shown_id: "blast-radius", + focused_id: null, + focus_requested_id: focus ? "blast-radius" : null, + uuid: "00000000-0000-4000-8000-000000000795", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_invalidate", + event: "ui.render", + uuid: "00000000-0000-4000-8000-000000000796", + session_id: WAKE_NATIVE_SESSION, + }), + ); + // Frames are handled in order, so a later notice proves the pane frame + // was handled without the turn ending. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: "Processing barrier.", + level: "warning", + uuid: "00000000-0000-4000-8000-000000000797", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until( + () => + harness.terminalEvents().length > 0 || + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice", ), + ); + const [terminal] = harness.terminalEvents(); + if (!focus) { + assert.equal(terminal, undefined); + return; + } + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.include(terminal.failure.message, "blast-radius"); + // The held tool call is abandoned by closing the query, never answered. + yield* Deferred.await(closed); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect("offers a cancelled wake once when an empty lifecycle result precedes its turn", () => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + // regression: #17531 a follow-up sent while the failed mod turn's process closes gets a new process + it.effect("runs a follow-up in a fresh query while the mod-blocked query is closing", () => + Effect.gen(function* () { + const releaseClose = yield* Deferred.make(); + const replacementClosedOld = yield* Deferred.make(); + let oldCloses = 0; + const harness = yield* makeWakeHarnessWithOptions({ + // The held CLI never answers an interrupt; closure must not need one. + interrupt: Effect.never, + close: (sdkMessages) => + Effect.suspend(() => + ++oldCloses === 2 ? Deferred.succeed(replacementClosedOld, undefined) : Effect.void, + ).pipe( + Effect.andThen(Deferred.await(releaseClose)), + Effect.andThen(Queue.shutdown(sdkMessages)), + ), + freshQueueOnReopen: true, + }); + // Added after the harness so it runs first: a failed assertion must not + // leave teardown waiting on the held close. + yield* Effect.addFinalizer(() => Deferred.succeed(releaseClose, undefined)); + const now = yield* DateTime.now; + const turnInput = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-mod-pane-blocked"), + text: "Run rm -r build", + attachments: [], + }); + yield* harness.runtime.startTurn(turnInput); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "ui_panes", + panes: [{ id: "blast-radius", title: "Blast Radius", plugin: "blast-radius", rows: 10 }], + shown_id: "blast-radius", + focused_id: null, + focus_requested_id: "blast-radius", + uuid: "00000000-0000-4000-8000-000000000798", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-empty-lifecycle"), - text: "Run two builds in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000171", - }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); + const followUp = yield* harness.runtime + .startTurn({ + ...turnInput, + attemptId: RunAttemptId.make("attempt-claude-after-mod-pane"), + providerTurnOrdinal: 2, + }) + .pipe(Effect.forkScoped); + // Reusing the closing process would offer the prompt to it instead. + yield* Effect.raceFirst( + Deferred.await(replacementClosedOld), + harness.until(() => harness.offeredMessages.length >= 2), + ); + assert.isTrue(yield* Deferred.isDone(replacementClosedOld)); + yield* Deferred.succeed(releaseClose, undefined); + yield* Fiber.join(followUp); + assert.equal(harness.processQueues.length, 2); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "after-mod-pane-result", result: "Done." }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000172", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000173" }), - ); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - assert.lengthOf( - harness.continuationRequests, - 1, - "the cancelled wake must not be offered again", - ); + // regression: #16897 a prompt whose uuid the session already holds must not hang or end early + it.effect("keeps a started prompt running until its result", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-started-prompt"), + text: "Bump this PR to the latest main.", + attachments: [], + }), + ); + const lifecycle = (state: string, uuid: string) => + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state, + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + yield* Queue.offer( + harness.sdkMessages, + lifecycle("queued", "00000000-0000-4000-8000-000000000791"), + ); + yield* Queue.offer( + harness.sdkMessages, + lifecycle("started", "00000000-0000-4000-8000-000000000792"), + ); + // The CLI can report the prompt completed before its turn's result. + yield* Queue.offer( + harness.sdkMessages, + lifecycle("completed", "00000000-0000-4000-8000-000000000793"), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000794", result: "Done." }), + user_message_uuid: harness.promptUuid(0), + }), + ); + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - uuid: "00000000-0000-4000-8000-000000000174", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000175" }), - ); - assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + it.effect("buffers wake output and requests a single continuation run", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-1"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.continuationRequests, 0); + + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 0); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + + yield* Queue.offer(harness.sdkMessages, wakeAssistant); + yield* harness.awaitContinuation(1); + assert.equal(harness.continuationRequests[0]?.threadId, harness.threadId); + assert.equal(harness.continuationRequests[0]?.providerThreadId, harness.providerThread.id); + assert.equal(harness.continuationRequests[0]?.driver, ClaudeAdapterV2.CLAUDE_PROVIDER); + assert.equal(harness.continuationRequests[0]?.detail, WAKE_SUMMARY); + + yield* harness.offerAndWait(wakeResult); + assert.lengthOf(harness.continuationRequests, 1); + assert.lengthOf(harness.terminalEvents(), 1); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("does not offer a cancelled wake again for its trailing empty lifecycle result", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + it.effect("starts the wake run when Claude opens the wake turn, before its output", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-trailing-lifecycle"), - text: "Run a build in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-init-1"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000176" }), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000177", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - assert.lengthOf( - harness.continuationRequests, - 1, - "a lifecycle result after the cancelled wake must not open another continuation", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 0); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + assert.equal(harness.continuationRequests[0]?.detail, WAKE_SUMMARY); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-init-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + assert.lengthOf(harness.terminalEvents(), 1); + + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.lengthOf(harness.continuationRequests, 1); + assert.isTrue( + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect.each([ - "before the cancelled wake's result", - "after the cancelled wake's result", - ] as const)( - "offers a subagent's wake that arrives behind a cancelled wake (notified %s)", - (notified) => - Effect.scoped( - Effect.gen(function* () { - const SUBAGENT_TASK_ID = "bg-agent"; - const SUBAGENT_TOOL_USE_ID = "toolu-bg-agent"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + it.effect("offers a later wake after an earlier wake's continuation dispatch failed", () => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const SECOND_SUMMARY = 'Background command "Second sleep" completed (exit code 0)'; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-later-subagent"), - text: "Run a build and an agent in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - task_type: "local_agent", - uuid: "00000000-0000-4000-8000-000000000181", - }), - ); - yield* harness.offerAndWait(turnOneResult); - yield* harness.awaitTerminal(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-dispatch-failed-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + description: "Second sleep", + uuid: "00000000-0000-4000-8000-000000000121", + }), + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); - const subagentNotification = claudeSdkFrame({ - ...wakeNotification, - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SUBAGENT_TASK_ID}.output`, - summary: "Agent finished", - uuid: "00000000-0000-4000-8000-000000000182", - }); - yield* harness.offerAndWait(wakeNotification); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - assert.lengthOf(harness.continuationRequests, 1); - if (notified === "before the cancelled wake's result") { - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* harness.offerAndWait(subagentNotification); - yield* harness.offerAndWait(wakeResult); - } else { - yield* harness.offerAndWait(wakeResult); - yield* harness.offerAndWait(subagentNotification); - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - } - assert.lengthOf( - harness.continuationRequests, - 2, - "the subagent's wake must get its own continuation", - ); - assert.equal(harness.continuationRequests[1]?.detail, "Agent finished"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + + // A failed dispatch never attaches the wake turn; clearIfCurrent is the only release. + const failed = harness.continuationRequests[0]!; + assert.isDefined(failed.clearIfCurrent); + yield* failed.clearIfCurrent!(); + yield* harness.until( + () => + !( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks ?? [] + ).some((task) => task.taskId === WAKE_TASK_ID), + ); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + summary: SECOND_SUMMARY, + uuid: "00000000-0000-4000-8000-000000000123", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000124" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect.each(["none", "before", "after", "sibling"] as const)( - "keeps an exited background command on the roster until its wake run starts (empty level %s notification)", - (emptyLevel) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const secondTaskId = "second-owed-wake"; - const taskIds = emptyLevel === "sibling" ? [WAKE_TASK_ID, secondTaskId] : [WAKE_TASK_ID]; - const wakeAttemptId = RunAttemptId.make("attempt-claude-wake-roster-2"); - const emptyRoster = claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [], - uuid: "00000000-0000-4000-8000-000000000204", - session_id: WAKE_NATIVE_SESSION, - }); + it.effect("keeps a newer wake's output when a stale continuation request is cleared", () => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-roster-1"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait(wakeTaskStarted); - if (emptyLevel === "sibling") - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: secondTaskId, - tool_use_id: "toolu_second_owed_wake", - uuid: "00000000-0000-4000-8000-000000000205", - }), - ); - const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; - assert.isDefined(awaitBackgroundTasks); - yield* awaitBackgroundTasks!({ - providerThread: harness.providerThread, - taskIds, - awaited: true, - }); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - const afterFirstTurn = harness.events.length; - if (emptyLevel === "before" || emptyLevel === "sibling") - yield* harness.offerAndWait(emptyRoster); - yield* harness.offerAndWait(wakeNotification); - if (emptyLevel === "after") yield* harness.offerAndWait(emptyRoster); - // Query replacement reads the internal roster, which the exit already cleared. - assert.isFalse(yield* harness.hasPendingBackgroundWork); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: wakeAttemptId, - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.awaitTerminal(2); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + description: "Second sleep", + uuid: "00000000-0000-4000-8000-000000000131", + }), + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); - const wakeStart = harness.events.findIndex( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.runAttemptId === wakeAttemptId, - ); - assert.isAbove(wakeStart, -1); - const rosters = harness.events.flatMap((event, index) => - event.type === "provider_thread.updated" && - event.providerThread.id === harness.providerThread.id && - index >= afterFirstTurn - ? [ - { - beforeWake: index < wakeStart, - pendingWork: event.pendingBackgroundWork === true, - taskIds: (event.providerThread.pendingBackgroundTasks ?? []).map((task) => [ - task.taskId, - task.awaited === true, - ]), - }, - ] - : [], - ); - assert.deepEqual( - rosters.filter((roster) => roster.beforeWake).map((roster) => roster.taskIds), - rosters - .filter((roster) => roster.beforeWake) - .map(() => taskIds.map((id) => [id, true])), - ); - assert.isTrue( - rosters.filter((roster) => roster.beforeWake).every((roster) => roster.pendingWork), - ); - assert.deepEqual( - rosters.at(-1)?.taskIds, - emptyLevel === "sibling" ? [[secondTaskId, true]] : [], - ); - if (emptyLevel === "sibling") { - assert.isTrue(rosters.at(-1)?.pendingWork); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: secondTaskId, - tool_use_id: "toolu_second_owed_wake", - uuid: "00000000-0000-4000-8000-000000000206", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000207" }), - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-owed-sibling-3"), - text: "Second command completed.", - attachments: [], - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.offerAndWait( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000208", - text: "Second command finished.", - }), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000209", - result: "Second command finished.", - origin: { kind: "task-notification" }, - }), - ); - yield* harness.awaitTerminal(3); - assert.deepEqual( - providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks, - [], - ); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.awaitTerminal(2); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000133", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000134" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000135", + text: "Second build done.", + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000136", + result: "Second build done.", + origin: { kind: "task-notification" }, + }), + ); + assert.lengthOf(harness.continuationRequests, 2); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + assert.isTrue( + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === "Second build done.", + ), + "clearing the first wake's request must not discard the second wake's output", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("offers the next wake when a cancelled wake's release arrives after it opened", () => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-late-release"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000141", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000142", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000143" }), + ); + assert.lengthOf(harness.continuationRequests, 1); + + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000144" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000145", result: "Done." }), + ); + assert.lengthOf( + harness.continuationRequests, + 2, + "the wake that opened before the cancelled wake's release must get its own continuation", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect.each([true, false])( - "carries a rejected wake rate limit into the continuation failure (event=%s)", - (standaloneEvent) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const resetsAt = 1790298600; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-limit-1"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* Queue.take(harness.terminalReceipts); + it.effect("does not offer a wake again when it is cancelled before its first root frame", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; - yield* Queue.offer(harness.sdkMessages, wakeNotification); - if (standaloneEvent) { - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { - status: "rejected", - rateLimitType: "five_hour", - resetsAt, - overageStatus: "rejected", - }, - uuid: "00000000-0000-4000-8000-000000000630", - session_id: WAKE_NATIVE_SESSION, - }), - ); - } - assert.lengthOf(harness.continuationRequests, 0); - yield* harness.offerAndWait( - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000631", - error: "rate_limit", - apiErrorParams: { - rate_limit_info: { - status: "rejected", - rateLimitType: "five_hour", - // A conflicting embedded time must not replace the event for this window. - resetsAt: standaloneEvent ? resetsAt + 3_600 : resetsAt, - }, - }, - }), - ); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000632", - result: "You've hit your session limit · resets 11:10am (Australia/Sydney)", - isError: true, - apiErrorStatus: 429, - terminalReason: "api_error", - origin: { kind: "task-notification" }, - }), - ); - assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-early-cancel"), + text: "Start an agent in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" })); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); - // An empty session-task lifecycle result arriving before T3 opens the - // wake run must not replace the root's terminal usage-limit result. - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000633", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + assert.lengthOf( + harness.continuationRequests, + 1, + "the cancelled wake must not be offered again", + ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-limit-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal?.status, "failed"); - if (terminal === undefined || terminal.status !== "failed") return; - assert.equal(terminal.failure.class, "usage_limit"); - assert.equal(terminal.failure.resetAt, "2026-09-25T01:10:00.000Z"); - if (standaloneEvent) { - const pause = yield* Queue.take(harness.systemNoticeReceipts); - assert.equal(pause.turnItem.type, "system_notice"); - if (pause.turnItem.type !== "system_notice") return; - assert.include(pause.turnItem.message, "This turn is paused until the 5-hour limit"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000146" }), + ); + assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect( - "dates a buffered wake gateway limit from its arrival, not the continuation replay", - () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + it.effect("offers a later task's wake when a cancelled wake never opens", () => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-gateway-1"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* Queue.take(harness.terminalReceipts); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-never-opens"), + text: "Start an agent and a build in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" })); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000151", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* harness.offerAndWait( - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000634", - error: "server_error", - }), - ); - assert.lengthOf(harness.continuationRequests, 1); - const arrivedAt = yield* DateTime.now; - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000635", - result: - 'API Error: 503 [cpa/claude-opus-5-5] [429]: {"type":"error","error":{"type":"rate_limit_error","message":"All credentials are cooling down"}} (reset after 2h54m21s)', - isError: true, - apiErrorStatus: 503, - terminalReason: "api_error", - origin: { kind: "task-notification" }, - }), - ); + // Claude never opens a wake for the agent's notification. + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - yield* TestClock.adjust("1 hour"); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-wake-gateway-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.equal(terminal.failure.class, "usage_limit"); - assert.equal( - terminal.failure.resetAt, - DateTime.formatIso( - DateTime.makeUnsafe( - DateTime.toEpochMillis(arrivedAt) + (2 * 3_600 + 54 * 60 + 21) * 1_000, - ), - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000152", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000153" }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000154", text: "Built." }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000155", result: "Built." }), + ); + assert.lengthOf( + harness.continuationRequests, + 2, + "the build's wake must get its own continuation", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () => - Effect.scoped( + it.effect.each([ + { ending: "notification", cancelled: "after its result" }, + { ending: "tool result", cancelled: "after its result" }, + { ending: "tool result", cancelled: "while the subagent ran" }, + ] as const)( + "does not replay a subagent that finished inside a cancelled wake (ended by $ending, cancelled $cancelled)", + ({ ending, cancelled }) => Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const SUBAGENT_TASK_ID = "fg-agent"; + const SUBAGENT_TOOL_USE_ID = "toolu-fg-agent"; const harness = yield* makeWakeHarness; const now = yield* DateTime.now; @@ -15367,121 +14516,348 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-4a"), - text: "Run the build in the background.", + attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent"), + text: "Run two builds in the background.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* Queue.offer(harness.sdkMessages, wakeResult); - yield* harness.awaitContinuation(1); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-4b"), - text: "How is the build going?", - attachments: [], - providerTurnOrdinal: 2, + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000161", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + // The first wake runs a subagent to completion before its result. + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + description: "Inspect build output", + subagent_type: "general-purpose", + task_type: "local_agent", + prompt: "Inspect the build output.", + uuid: "00000000-0000-4000-8000-000000000162", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000168", + text: "Reading the build log.", + }), + parent_tool_use_id: SUBAGENT_TOOL_USE_ID, }), ); + if (cancelled === "while the subagent ran") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + yield* harness.offerAndWait( + ending === "notification" + ? claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + status: "completed", + output_file: "/tmp/fg-agent.output", + summary: "Inspected", + uuid: "00000000-0000-4000-8000-000000000163", + session_id: WAKE_NATIVE_SESSION, + }) + : claudeSdkFrame({ + type: "user", + uuid: "00000000-0000-4000-8000-000000000163", + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: SUBAGENT_TOOL_USE_ID, + content: "Inspected", + }, + ], + }, + }), + ); + yield* harness.offerAndWait(wakeResult); + if (cancelled === "after its result") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } - yield* harness.until(() => harness.offeredMessages.length === 2); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000105", - result: "The build passed; nothing else pending.", + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000164", }), ); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.isFalse( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, - ), + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000165" }), ); - + assert.lengthOf(harness.continuationRequests, 2); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-4c"), + attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent-2"), text: "Background task completed.", attachments: [], - providerTurnOrdinal: 3, + providerTurnOrdinal: 2, messageCreatedBy: "agent", messageCreationSource: "provider", }), ); - yield* harness.awaitTerminal(3); - assert.equal(harness.terminalEvents()[2]?.status, "completed"); - assert.lengthOf(harness.offeredMessages, 2); - assert.isTrue( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, - ), - ); - assert.isFalse( - harness.events.some( - (event) => - event.type !== "provider_thread.updated" && - JSON.stringify(event).includes(WAKE_TASK_ID), - ), + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000166", + text: "Second build done.", + }), ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - // The continuation settled with no result of its own, so a late suggestion belongs to B. yield* harness.offerAndWait( - claudeSdkFrame({ - type: "prompt_suggestion", - suggestion: "Check the build logs", - uuid: "00000000-0000-4000-8000-000000000692", - session_id: WAKE_NATIVE_SESSION, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000167", + result: "Second build done.", + origin: { kind: "task-notification" }, }), ); - const userTurn = makeClaudeTestTurnInput({ + yield* harness.awaitTerminal(2); + + const subagentStatuses = harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === SUBAGENT_TASK_ID + ? [event.subagent.status] + : [], + ); + assert.notInclude( + subagentStatuses, + "running", + "a subagent that finished in the cancelled wake must not be replayed as running", + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("offers a cancelled wake once when an empty lifecycle result precedes its turn", () => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-4d"), - text: "Ship it.", + attemptId: RunAttemptId.make("attempt-claude-wake-empty-lifecycle"), + text: "Run two builds in the background.", attachments: [], - providerTurnOrdinal: 4, - }); - yield* harness.runtime.startTurn(userTurn); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000693", result: "Shipped." }), + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000171", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000172", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000173" }), + ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + assert.lengthOf( + harness.continuationRequests, + 1, + "the cancelled wake must not be offered again", + ); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000174", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000175" }), + ); + assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("does not offer a cancelled wake again for its trailing empty lifecycle result", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-trailing-lifecycle"), + text: "Run a build in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000176" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000177", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + assert.lengthOf( + harness.continuationRequests, + 1, + "a lifecycle result after the cancelled wake must not open another continuation", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each([ + "before the cancelled wake's result", + "after the cancelled wake's result", + ] as const)( + "offers a subagent's wake that arrives behind a cancelled wake (notified %s)", + (notified) => + Effect.gen(function* () { + const SUBAGENT_TASK_ID = "bg-agent"; + const SUBAGENT_TOOL_USE_ID = "toolu-bg-agent"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-later-subagent"), + text: "Run a build and an agent in the background.", + attachments: [], + }), ); - yield* harness.awaitTerminal(4); - yield* Queue.offer( - harness.sdkMessages, + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( claudeSdkFrame({ - type: "prompt_suggestion", - suggestion: "Open the release notes", - uuid: "00000000-0000-4000-8000-000000000694", - session_id: WAKE_NATIVE_SESSION, + ...wakeTaskStarted, + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000181", }), ); - yield* harness.until(() => - harness.events.some((event) => event.type === "prompt_suggestion.updated"), - ); - assert.deepEqual( - harness.events.flatMap((event) => - event.type === "prompt_suggestion.updated" ? [[event.runId, event.text]] : [], - ), - [[userTurn.runId, "Open the release notes"]], + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + const subagentNotification = claudeSdkFrame({ + ...wakeNotification, + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SUBAGENT_TASK_ID}.output`, + summary: "Agent finished", + uuid: "00000000-0000-4000-8000-000000000182", + }); + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + assert.lengthOf(harness.continuationRequests, 1); + if (notified === "before the cancelled wake's result") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait(subagentNotification); + yield* harness.offerAndWait(wakeResult); + } else { + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait(subagentNotification); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + assert.lengthOf( + harness.continuationRequests, + 2, + "the subagent's wake must get its own continuation", ); + assert.equal(harness.continuationRequests[1]?.detail, "Agent finished"); }).pipe( Effect.provide( Layer.mergeAll( @@ -15492,330 +14868,288 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect("settles a continuation whose wake turn a user turn absorbed", () => - Effect.scoped( + it.effect.each(["none", "before", "after", "sibling"] as const)( + "keeps an exited background command on the roster until its wake run starts (empty level %s notification)", + (emptyLevel) => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; + const secondTaskId = "second-owed-wake"; + const taskIds = emptyLevel === "sibling" ? [WAKE_TASK_ID, secondTaskId] : [WAKE_TASK_ID]; + const wakeAttemptId = RunAttemptId.make("attempt-claude-wake-roster-2"); + const emptyRoster = claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000204", + session_id: WAKE_NATIVE_SESSION, + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-1"), + attemptId: RunAttemptId.make("attempt-claude-wake-roster-1"), text: "Run the build in the background.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* harness.offerAndWait(wakeTaskStarted); + if (emptyLevel === "sibling") + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: secondTaskId, + tool_use_id: "toolu_second_owed_wake", + uuid: "00000000-0000-4000-8000-000000000205", + }), + ); + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + assert.isDefined(awaitBackgroundTasks); + yield* awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds, + awaited: true, + }); yield* Queue.offer(harness.sdkMessages, turnOneResult); yield* harness.awaitTerminal(1); + const afterFirstTurn = harness.events.length; + if (emptyLevel === "before" || emptyLevel === "sibling") + yield* harness.offerAndWait(emptyRoster); + yield* harness.offerAndWait(wakeNotification); + if (emptyLevel === "after") yield* harness.offerAndWait(emptyRoster); + // Query replacement reads the internal roster, which the exit already cleared. + assert.isFalse(yield* harness.hasPendingBackgroundWork); yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.awaitContinuation(1); - - // Claude folds this prompt into the wake turn it already opened, so one result ends both. yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-2"), - text: "Any update on the pull request?", + attemptId: wakeAttemptId, + text: "Background task completed.", attachments: [], providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", }), ); - yield* harness.until(() => harness.offeredMessages.length === 2); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000140", - result: "Checks passed and the pull request is up to date.", - }), - ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); yield* harness.awaitTerminal(2); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-3"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), + const wakeStart = harness.events.findIndex( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.runAttemptId === wakeAttemptId, + ); + assert.isAbove(wakeStart, -1); + const rosters = harness.events.flatMap((event, index) => + event.type === "provider_thread.updated" && + event.providerThread.id === harness.providerThread.id && + index >= afterFirstTurn + ? [ + { + beforeWake: index < wakeStart, + pendingWork: event.pendingBackgroundWork === true, + taskIds: (event.providerThread.pendingBackgroundTasks ?? []).map((task) => [ + task.taskId, + task.awaited === true, + ]), + }, + ] + : [], + ); + assert.deepEqual( + rosters.filter((roster) => roster.beforeWake).map((roster) => roster.taskIds), + rosters.filter((roster) => roster.beforeWake).map(() => taskIds.map((id) => [id, true])), ); - yield* harness.awaitTerminal(3); - assert.equal(harness.terminalEvents()[2]?.status, "completed"); assert.isTrue( - harness.events.some( - (event) => - event.type === "message.updated" && event.message.text === WAKE_ASSISTANT_TEXT, - ), + rosters.filter((roster) => roster.beforeWake).every((roster) => roster.pendingWork), ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect.each(["before", "after"] as const)( - "offers a later wake when a wake a user turn absorbed is cancelled %s that turn ends", - (cancelled) => - Effect.scoped( - Effect.gen(function* () { - const SECOND_TASK_ID = "b2ndwake"; - const SECOND_TOOL_USE_ID = "toolu_second_wake"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-1"), - text: "Run two builds in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer( - harness.sdkMessages, + assert.deepEqual( + rosters.at(-1)?.taskIds, + emptyLevel === "sibling" ? [[secondTaskId, true]] : [], + ); + if (emptyLevel === "sibling") { + assert.isTrue(rosters.at(-1)?.pendingWork); + yield* harness.offerAndWait( claudeSdkFrame({ - ...wakeTaskStarted, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000191", + ...wakeNotification, + task_id: secondTaskId, + tool_use_id: "toolu_second_owed_wake", + uuid: "00000000-0000-4000-8000-000000000206", }), ); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* harness.awaitTerminal(1); - yield* harness.offerAndWait(wakeTurnInit); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.awaitContinuation(1); - + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000207" }), + ); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-2"), - text: "Any update on the pull request?", + attemptId: RunAttemptId.make("attempt-claude-owed-sibling-3"), + text: "Second command completed.", attachments: [], - providerTurnOrdinal: 2, + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", }), ); - yield* harness.until(() => harness.offeredMessages.length === 2); - if (cancelled === "before") { - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - } - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000192", - result: "Checks passed and the pull request is up to date.", + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000208", + text: "Second command finished.", }), ); - yield* harness.awaitTerminal(2); - if (cancelled === "after") { - yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); - } - yield* harness.offerAndWait( - claudeSdkFrame({ - ...wakeNotification, - task_id: SECOND_TASK_ID, - tool_use_id: SECOND_TOOL_USE_ID, - output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, - uuid: "00000000-0000-4000-8000-000000000193", + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000209", + result: "Second command finished.", + origin: { kind: "task-notification" }, }), ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000194" }), + yield* harness.awaitTerminal(3); + assert.deepEqual( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks, + [], ); - assert.lengthOf(harness.continuationRequests, 2, "the later wake must be offered"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => - Effect.scoped( + it.effect.each([true, false])( + "carries a rejected wake rate limit into the continuation failure (event=%s)", + (standaloneEvent) => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const probeAssistantText = "Probe after stale task-notification result."; - const recoveryAssistantText = "Recovered after the interrupt; continuing."; - const staleResultText = STALE_TASK_NOTIFICATION_RESULT_TEXT; - const hasMessageText = (text: string) => - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === text, - ); + const resetsAt = 1790298600; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-stale-notif-1"), - text: "Continue after interrupt.", + attemptId: RunAttemptId.make("attempt-claude-wake-limit-1"), + text: "Run the build in the background.", attachments: [], }), ); - yield* harness.until(() => harness.offeredMessages.length === 1); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* Queue.take(harness.terminalReceipts); - // After interrupt recovery, stale task notifications and their results can precede the root stream. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: "task-stale-stopped", - tool_use_id: "toolu-stale-stopped", - status: "stopped", - output_file: "/tmp/task-stale-stopped.log", - summary: "", - uuid: "00000000-0000-4000-8000-000000000107", - session_id: WAKE_NATIVE_SESSION, + yield* Queue.offer(harness.sdkMessages, wakeNotification); + if (standaloneEvent) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "rate_limit_event", + rate_limit_info: { + status: "rejected", + rateLimitType: "five_hour", + resetsAt, + overageStatus: "rejected", + }, + uuid: "00000000-0000-4000-8000-000000000630", + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + assert.lengthOf(harness.continuationRequests, 0); + yield* harness.offerAndWait( + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000631", + error: "rate_limit", + apiErrorParams: { + rate_limit_info: { + status: "rejected", + rateLimitType: "five_hour", + // A conflicting embedded time must not replace the event for this window. + resetsAt: standaloneEvent ? resetsAt + 3_600 : resetsAt, + }, + }, }), ); - yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-00000000010a", - text: probeAssistantText, + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000632", + result: "You've hit your session limit · resets 11:10am (Australia/Sydney)", + isError: true, + apiErrorStatus: 429, + terminalReason: "api_error", + origin: { kind: "task-notification" }, }), ); + assert.lengthOf(harness.continuationRequests, 1); - yield* harness.until(() => hasMessageText(probeAssistantText)); - assert.lengthOf(harness.terminalEvents(), 0); - assert.isFalse(hasMessageText(staleResultText)); - - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000108", - text: recoveryAssistantText, - }), - ); - yield* Queue.offer( - harness.sdkMessages, + // An empty session-task lifecycle result arriving before T3 opens the + // wake run must not replace the root's terminal usage-limit result. + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait( makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000109", - result: recoveryAssistantText, + uuid: "00000000-0000-4000-8000-000000000633", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, }), ); - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue(hasMessageText(recoveryAssistantText)); - assert.isFalse(hasMessageText(staleResultText)); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect( - "emits one interrupted terminal for a positive task-notification result racing interrupt", - () => - Effect.scoped( - Effect.gen(function* () { - const closeGate = yield* Deferred.make(); - const testScope = yield* Scope.Scope; - yield* Scope.addFinalizer(testScope, Deferred.succeed(closeGate, undefined)); - const interruptStarted = yield* Deferred.make(); - const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => - Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), - stopTask: () => Effect.void, - interrupt: Deferred.succeed(interruptStarted, undefined), - }); - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-interrupt-positive-notif"); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId, - text: "Stop this task.", - attachments: [], - }), - ); - yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* Deferred.await(interruptStarted); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000115", - result: "Late result after interrupt.", - numTurns: 7, - origin: { kind: "task-notification" }, - }), - ); - const terminalized = Exit.isSuccess(yield* harness.awaitTerminal(1).pipe(Effect.exit)); - yield* Deferred.succeed(closeGate, undefined); - assert.isTrue(terminalized); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - assert.lengthOf(harness.terminalEvents(), 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-limit-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal?.status, "failed"); + if (terminal === undefined || terminal.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal(terminal.failure.resetAt, "2026-09-25T01:10:00.000Z"); + if (standaloneEvent) { + const pause = yield* Queue.take(harness.systemNoticeReceipts); + assert.equal(pause.turnItem.type, "system_notice"); + if (pause.turnItem.type !== "system_notice") return; + assert.include(pause.turnItem.message, "This turn is paused until the 5-hour limit"); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("settles a continuation turn immediately when no wake output is buffered", () => - Effect.scoped( + it.effect( + "dates a buffered wake gateway limit from its arrival, not the continuation replay", + () => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; @@ -15825,17 +15159,62 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-wake-3"), + attemptId: RunAttemptId.make("attempt-claude-wake-gateway-1"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* Queue.take(harness.terminalReceipts); + + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* harness.offerAndWait( + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000634", + error: "server_error", + }), + ); + assert.lengthOf(harness.continuationRequests, 1); + const arrivedAt = yield* DateTime.now; + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000635", + result: + 'API Error: 503 [cpa/claude-opus-5-5] [429]: {"type":"error","error":{"type":"rate_limit_error","message":"All credentials are cooling down"}} (reset after 2h54m21s)', + isError: true, + apiErrorStatus: 503, + terminalReason: "api_error", + origin: { kind: "task-notification" }, + }), + ); + + yield* TestClock.adjust("1 hour"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-wake-gateway-2"), text: "Background task completed.", attachments: [], + providerTurnOrdinal: 2, messageCreatedBy: "agent", messageCreationSource: "provider", }), ); - - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.lengthOf(harness.offeredMessages, 0); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal( + terminal.failure.resetAt, + DateTime.formatIso( + DateTime.makeUnsafe( + DateTime.toEpochMillis(arrivedAt) + (2 * 3_600 + 54 * 60 + 21) * 1_000, + ), + ), + ); }).pipe( Effect.provide( Layer.mergeAll( @@ -15846,441 +15225,298 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - const makeSubagentAssistantFrames = (input: { - readonly parentToolUseId: string; - readonly uuid: string; - readonly messageId?: string; - readonly text?: string; - readonly bashToolUseId?: string; - }): ReadonlyArray => - [ - ...(input.text === undefined ? [] : [{ type: "text", text: input.text }]), - ...(input.bashToolUseId === undefined - ? [] - : [ - { - type: "tool_use", - id: input.bashToolUseId, - name: "Bash", - input: { command: "git log -5" }, - }, - ]), - ].map((block, index) => - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: input.messageId ?? `msg_${input.uuid}`, - type: "message", - role: "assistant", - content: [block], - }, - parent_tool_use_id: input.parentToolUseId, - uuid: index === 0 ? input.uuid : `${input.uuid}:${index}`, - session_id: WAKE_NATIVE_SESSION, - }), - ); - const makeSubagentToolResultFrame = (input: { - readonly parentToolUseId: string; - readonly uuid: string; - readonly toolUseId: string; - }) => - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [{ type: "tool_result", tool_use_id: input.toolUseId, content: "ok" }], - }, - parent_tool_use_id: input.parentToolUseId, - uuid: input.uuid, - session_id: WAKE_NATIVE_SESSION, - }); - const makeSubagentTaskStartedFrame = (input: { - readonly taskId: string; - readonly toolUseId: string; - readonly uuid: string; - }) => - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: input.taskId, - tool_use_id: input.toolUseId, - description: "Audit recent commits", - subagent_type: "general-purpose", - is_backgrounded: true, - task_type: "local_agent", - prompt: "Audit the last five commits.", - uuid: input.uuid, - session_id: WAKE_NATIVE_SESSION, - }); - const makeSubagentNotificationFrame = (input: { - readonly taskId: string; - readonly toolUseId: string; - readonly summary: string; - readonly uuid: string; - }) => - claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: input.taskId, - tool_use_id: input.toolUseId, - status: "completed", - output_file: `/tmp/${input.taskId}.output`, - summary: input.summary, - uuid: input.uuid, - session_id: WAKE_NATIVE_SESSION, - }); - const subagentRouting = ( - events: ReadonlyArray, - nativeToolIds: ReadonlyArray, - ) => { - const childThreadId = - events.find((event) => event.type === "subagent.updated")?.subagent.childThreadId ?? - undefined; - const toolThreadIds = new Map>(); - for (const event of events) { - const nativeId = - event.type === "turn_item.updated" ? event.turnItem.nativeItemRef?.nativeId : undefined; - if (event.type === "turn_item.updated" && nativeId && nativeToolIds.includes(nativeId)) { - toolThreadIds.set( - nativeId, - (toolThreadIds.get(nativeId) ?? new Set()).add(event.turnItem.threadId), - ); - } - } - const assistantTexts = (threadId: string | undefined) => - events.flatMap((event) => - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.threadId === threadId - ? [event.message.text] - : [], + it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-4a"), + text: "Run the build in the background.", + attachments: [], + }), ); - return { childThreadId, toolThreadIds, assistantTexts }; - }; + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* Queue.offer(harness.sdkMessages, wakeResult); + yield* harness.awaitContinuation(1); - it.effect.each([ - { label: "an empty one", quotaFailureFirst: false }, - { label: "a quota failure and an empty one", quotaFailureFirst: true }, - ])( - "keeps the wake run open for the turn Claude opens right after $label", - ({ quotaFailureFirst }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const subagents = [ - { taskId: "task-wake-pair-a", toolUseId: "toolu_wake_pair_a" }, - { taskId: "task-wake-pair-b", toolUseId: "toolu_wake_pair_b" }, - ]; - const wakeAttempt = RunAttemptId.make("attempt-claude-wake-pair-2"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-4b"), + text: "How is the build going?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-pair-1"), - text: "Audit both in the background.", - attachments: [], - }), - ); - for (const [index, subagent] of subagents.entries()) { - yield* Queue.offer( - harness.sdkMessages, - makeSubagentTaskStartedFrame({ - ...subagent, - uuid: `00000000-0000-4000-8000-00000000095${index}`, - }), - ); - } - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000952", result: "Started." }), - ); - yield* harness.awaitTerminal(1); - - // Both subagents end together. Claude runs an empty turn for the first - // notification and opens the real one a millisecond later, all before - // the wake run attaches. - for (const [index, subagent] of subagents.entries()) { - yield* Queue.offer( - harness.sdkMessages, - makeSubagentNotificationFrame({ - ...subagent, - summary: "AUDITED", - uuid: `00000000-0000-4000-8000-00000000096${index}`, - }), - ); - } - // A rejected wake that precedes the empty turn still must not settle - // the run the live turn owns. - if (quotaFailureFirst) { - yield* harness.offerAndWait( - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000964", - error: "rate_limit", - }), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000965", - result: "You've hit your session limit · resets 11:10am (Australia/Sydney)", - isError: true, - apiErrorStatus: 429, - terminalReason: "api_error", - origin: { kind: "task-notification" }, - }), - ); - } - yield* Queue.offer(harness.sdkMessages, wakeTurnInit); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000962", - result: "", - numTurns: 0, - origin: { kind: "task-notification" }, - terminalReason: null, - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000963" }), - ); - assert.lengthOf(harness.continuationRequests, 1); + yield* harness.until(() => harness.offeredMessages.length === 2); + assert.lengthOf(harness.terminalEvents(), 1); + assert.isTrue(yield* harness.hasPendingBackgroundWork); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: wakeAttempt, - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - // Claude is still thinking, so the run stays working rather than - // settling with nothing to show. - assert.lengthOf(harness.terminalEvents(), 1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000105", + result: "The build passed; nothing else pending.", + }), + ); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.isFalse( + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, + ), + ); - yield* harness.offerAndWait(wakeAssistant); - yield* harness.offerAndWait(wakeResult); - yield* harness.awaitTerminal(2); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.lengthOf(harness.continuationRequests, 1); - assert.isTrue( - harness.events.some( - (event) => - event.type === "message.updated" && - event.message.runId === RunId.make(`run-${wakeAttempt}`) && - event.message.text === WAKE_RESULT_TEXT, - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-4c"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + assert.equal(harness.terminalEvents()[2]?.status, "completed"); + assert.lengthOf(harness.offeredMessages, 2); + assert.isTrue( + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, ), - ), - ); + ); + assert.isFalse( + harness.events.some( + (event) => + event.type !== "provider_thread.updated" && + JSON.stringify(event).includes(WAKE_TASK_ID), + ), + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); - // A Stop closes the first process, and a turn replaces it before its stream ends. - const stopRacedByReplacementTurn = (label: string) => - Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: `t3-claude-v2-${label}-`, - }); - const processQueues: Array> = []; - // The first two processes exit only when the test ends their streams. - const closeRequested = [yield* Deferred.make(), yield* Deferred.make()]; - const events: Array = []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator: yield* IdAllocator.IdAllocatorV2, - continuationRequests: { offer: () => Effect.void }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - const closeSignal = closeRequested[processQueues.length]; - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - stopTask: () => Effect.void, - mcpServerStatus: Effect.die("unexpected MCP server status"), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - interrupt: Effect.void, - close: - closeSignal === undefined - ? Queue.shutdown(sdkMessages) - : Deferred.succeed(closeSignal, undefined).pipe(Effect.asVoid), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make(`thread-claude-${label}`); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make(`provider-session-claude-${label}`), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + // The continuation settled with no result of its own, so a late suggestion belongs to B. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "prompt_suggestion", + suggestion: "Check the build logs", + uuid: "00000000-0000-4000-8000-000000000692", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const userTurn = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-4d"), + text: "Ship it.", + attachments: [], + providerTurnOrdinal: 4, }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe(Effect.andThen(changes.notify)), + yield* harness.runtime.startTurn(userTurn); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000693", result: "Shipped." }), + ); + yield* harness.awaitTerminal(4); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "prompt_suggestion", + suggestion: "Open the release notes", + uuid: "00000000-0000-4000-8000-000000000694", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until(() => + harness.events.some((event) => event.type === "prompt_suggestion.updated"), + ); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "prompt_suggestion.updated" ? [[event.runId, event.text]] : [], ), - Effect.forkScoped, + [[userTurn.runId, "Open the release notes"]], ); - const terminals = () => events.filter((event) => event.type === "turn.terminal"); - const subagentStatus = (taskId: string) => { - const latest = events.findLast( - (event) => - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === taskId, - ); - return latest?.type === "subagent.updated" ? latest.subagent.status : undefined; - }; + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("settles a continuation whose wake turn a user turn absorbed", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - yield* runtime.startTurn( + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ - threadId, - providerThread, + threadId: harness.threadId, + providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make(`attempt-claude-${label}-a`), - text: "Audit the last commits in the background.", + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-1"), + text: "Run the build in the background.", attachments: [], }), ); - yield* Queue.offer( - processQueues[0]!, - makeSubagentTaskStartedFrame({ - taskId: "raced-agent", - toolUseId: "toolu-raced-agent", - uuid: "00000000-0000-4000-8000-000000002801", + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.awaitContinuation(1); + + // Claude folds this prompt into the wake turn it already opened, so one result ends both. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-2"), + text: "Any update on the pull request?", + attachments: [], + providerTurnOrdinal: 2, }), ); + yield* harness.until(() => harness.offeredMessages.length === 2); yield* Queue.offer( - processQueues[0]!, + harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002802", - result: "Launched the audit.", + uuid: "00000000-0000-4000-8000-000000000140", + result: "Checks passed and the pull request is up to date.", }), ); - yield* changes.until( - () => terminals().length === 1 && subagentStatus("raced-agent") === "running", - ); + yield* harness.awaitTerminal(2); - const stop = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: terminals()[0]!.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(closeRequested[0]!); - yield* runtime.startTurn( + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, + threadId: harness.threadId, + providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make(`attempt-claude-${label}-b`), - text: "Resume after the limit reset.", + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-3"), + text: "Background task completed.", attachments: [], - providerTurnOrdinal: 2, + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", }), ); - assert.lengthOf(processQueues, 2); - yield* Queue.offer( - processQueues[1]!, - makeSubagentTaskStartedFrame({ - taskId: "own-agent", - toolUseId: "toolu-own-agent", - uuid: "00000000-0000-4000-8000-000000002804", - }), + yield* harness.awaitTerminal(3); + assert.equal(harness.terminalEvents()[2]?.status, "completed"); + assert.isTrue( + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === WAKE_ASSISTANT_TEXT, + ), ); - yield* changes.until(() => subagentStatus("own-agent") === "running"); - const exitProcess = (index: number, stopping: Fiber.Fiber) => - Queue.shutdown(processQueues[index]!).pipe(Effect.andThen(Fiber.join(stopping))); - return { - runtime, - threadId, - providerThread, - processQueues, - closeRequested, - changes, - terminals, - subagentStatus, - exitFirstProcess: exitProcess(0, stop), - exitProcess, - now, - }; - }); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each(["before", "after"] as const)( + "offers a later wake when a wake a user turn absorbed is cancelled %s that turn ends", + (cancelled) => + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000191", + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.awaitContinuation(1); - // regression: #28331 a subagent whose process is gone must not stay running forever - it.effect("ends a subagent whose process a Stop closed while a new turn replaced it", () => - Effect.scoped( - Effect.gen(function* () { - const { processQueues, changes, terminals, subagentStatus, exitFirstProcess } = - yield* stopRacedByReplacementTurn("raced-stop-replacement-close"); - yield* exitFirstProcess; - // The replacement's result follows the stopped process's exit on the event stream. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-2"), + text: "Any update on the pull request?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + if (cancelled === "before") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } yield* Queue.offer( - processQueues[1]!, + harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000002803", - result: "Resumed.", + uuid: "00000000-0000-4000-8000-000000000192", + result: "Checks passed and the pull request is up to date.", }), ); - yield* changes.until(() => terminals().length === 2); + yield* harness.awaitTerminal(2); + if (cancelled === "after") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } - assert.strictEqual( - subagentStatus("raced-agent"), - "cancelled", - "the Stop ended the subagent's process, but the subagent is not cancelled", + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000193", + }), ); - assert.strictEqual( - subagentStatus("own-agent"), - "running", - "the replacement process still runs its own subagent", + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000194" }), ); + assert.lengthOf(harness.continuationRequests, 2, "the later wake must be offered"); }).pipe( Effect.provide( Layer.mergeAll( @@ -16291,273 +15527,141 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - // regression: #28331 Stop must clear a subagent whose process is gone - it.effect("stops a subagent whose process a Stop closed while a new turn replaced it", () => - Effect.scoped( - Effect.gen(function* () { - const { runtime, providerThread, exitFirstProcess } = yield* stopRacedByReplacementTurn( - "raced-stop-replacement-stop-subagent", - ); - yield* exitFirstProcess; - const stopped = yield* runtime.stopSubagent!({ - providerThread: { ...providerThread, status: "active" }, - nativeTaskId: "raced-agent", - }).pipe( - Effect.map((outcome) => outcome?.status ?? "no outcome"), - Effect.catch((error) => - Effect.succeed(`refused: ${"detail" in error ? error.detail : error.message}`), - ), + it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const probeAssistantText = "Probe after stale task-notification result."; + const recoveryAssistantText = "Recovered after the interrupt; continuing."; + const staleResultText = STALE_TASK_NOTIFICATION_RESULT_TEXT; + const hasMessageText = (text: string) => + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === text, ); - assert.strictEqual(stopped, "cancelled", "Stop of a subagent whose process is gone"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - // regression: #28331 a process that exits late ends only the subagents it ran - it.effect("leaves a stopping replacement's subagent to that replacement's exit", () => - Effect.scoped( - Effect.gen(function* () { - const { - runtime, - threadId, - providerThread, - processQueues, - closeRequested, - changes, - terminals, - subagentStatus, - exitFirstProcess, - exitProcess, + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, now, - } = yield* stopRacedByReplacementTurn("raced-stop-replacement-chain"); - const activeThread = { ...providerThread, status: "active" as const }; - const finishTurn = (index: number, turns: number, uuid: string) => - Queue.offer(processQueues[index]!, makeResultFrame({ uuid, result: "Done." })).pipe( - Effect.andThen(changes.until(() => terminals().length === turns)), - ); - const startTurn = (label: string, providerTurnOrdinal: number) => - runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: activeThread, - now, - attemptId: RunAttemptId.make(`attempt-claude-raced-stop-replacement-chain-${label}`), - text: "Carry on.", - attachments: [], - providerTurnOrdinal, - }), - ); + attemptId: RunAttemptId.make("attempt-claude-stale-notif-1"), + text: "Continue after interrupt.", + attachments: [], + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 1); - yield* finishTurn(1, 2, "00000000-0000-4000-8000-000000002805"); - const stopSecond = yield* runtime - .interruptTurn({ - providerThread: activeThread, - providerTurnId: terminals()[1]!.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(closeRequested[1]!); - yield* startTurn("c", 3); - assert.lengthOf(processQueues, 3); - - yield* exitFirstProcess; - yield* finishTurn(2, 3, "00000000-0000-4000-8000-000000002806"); - assert.strictEqual( - subagentStatus("raced-agent"), - "cancelled", - "the first process exited after a Stop, but its subagent is not cancelled", - ); - assert.strictEqual( - subagentStatus("own-agent"), - "running", - "the first process ended a subagent the second process still ran", - ); + // After interrupt recovery, stale task notifications and their results can precede the root stream. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: "task-stale-stopped", + tool_use_id: "toolu-stale-stopped", + status: "stopped", + output_file: "/tmp/task-stale-stopped.log", + summary: "", + uuid: "00000000-0000-4000-8000-000000000107", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult); + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-00000000010a", + text: probeAssistantText, + }), + ); - yield* exitProcess(1, stopSecond); - yield* startTurn("d", 4); - yield* finishTurn(2, 4, "00000000-0000-4000-8000-000000002807"); - assert.strictEqual( - subagentStatus("own-agent"), - "cancelled", - "the second process exited after a Stop, but its subagent is not cancelled", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.until(() => hasMessageText(probeAssistantText)); + assert.lengthOf(harness.terminalEvents(), 0); + assert.isFalse(hasMessageText(staleResultText)); + + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000108", + text: recoveryAssistantText, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000109", + result: recoveryAssistantText, + }), + ); + + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.isTrue(hasMessageText(recoveryAssistantText)); + assert.isFalse(hasMessageText(staleResultText)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("streams a background subagent's work while the root turn is idle", () => - Effect.scoped( + it.effect( + "emits one interrupted terminal for a positive task-notification result racing interrupt", + () => Effect.gen(function* () { - const TASK_ID = "task-live-idle"; - const TOOL_USE_ID = "toolu-live-idle"; - const STRADDLING_BASH = "toolu-live-straddling-bash"; - const IDLE_BASH = "toolu-live-idle-bash"; - const harness = yield* makeWakeHarness; + const closeGate = yield* Deferred.make(); + const testScope = yield* Scope.Scope; + yield* Scope.addFinalizer(testScope, Deferred.succeed(closeGate, undefined)); + const interruptStarted = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + stopTask: () => Effect.void, + interrupt: Deferred.succeed(interruptStarted, undefined), + }); + const idAllocator = yield* IdAllocator.IdAllocatorV2; const now = yield* DateTime.now; - const latestToolItem = (nativeId: string) => - harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === nativeId, - ); + const attemptId = RunAttemptId.make("attempt-claude-interrupt-positive-notif"); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-live-idle-1"), - text: "Audit in the background.", + attemptId, + text: "Stop this task.", attachments: [], }), ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000951", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000952", - bashToolUseId: STRADDLING_BASH, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000953", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - - for (const frame of [ - makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000954", - toolUseId: STRADDLING_BASH, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000955", - text: "Still auditing.", - bashToolUseId: IDLE_BASH, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: TASK_ID, - description: "Reading the last commits", - uuid: "00000000-0000-4000-8000-000000000956", - session_id: WAKE_NATIVE_SESSION, - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.until(() => { - const event = latestToolItem(IDLE_BASH); - return event?.type === "turn_item.updated" && event.turnItem.status === "running"; - }); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.progress === "Reading the last commits", - ), - ); - const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]); - assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]); - const straddling = latestToolItem(STRADDLING_BASH); - const straddlingItem = - straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined; - assert.equal(straddlingItem?.status, "completed"); - assert.equal( - straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined, - "git log -5", - ); - assert.equal(harness.continuationRequests.length, 0); - - for (const frame of [ - makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000957", - toolUseId: IDLE_BASH, - }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: "Still auditing.", - uuid: "00000000-0000-4000-8000-000000000958", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitContinuation(1); + yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* Deferred.await(interruptStarted); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000959", - result: "The auditor finished.", - }), - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-live-idle-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", + uuid: "00000000-0000-4000-8000-000000000115", + result: "Late result after interrupt.", + numTurns: 7, + origin: { kind: "task-notification" }, }), ); - yield* harness.awaitTerminal(2); - - const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]); - assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [ - "Still auditing.", - ]); - for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) { - assert.deepEqual( - [...(finalRouting.toolThreadIds.get(nativeId) ?? [])], - [finalRouting.childThreadId], - ); - const statuses = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === nativeId - ? [`${event.turnItem.type}:${event.turnItem.status}`] - : [], - ); - assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]); - } - const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated"); - assert.equal( - finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status, - "completed", - ); + const terminalized = Exit.isSuccess(yield* harness.awaitTerminal(1).pipe(Effect.exit)); + yield* Deferred.succeed(closeGate, undefined); + assert.isTrue(terminalized); + assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); + assert.lengthOf(harness.terminalEvents(), 1); }).pipe( Effect.provide( Layer.mergeAll( @@ -16568,153 +15672,249 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("settles a continuation turn immediately when no wake output is buffered", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-3"), + text: "Background task completed.", + attachments: [], + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.lengthOf(harness.offeredMessages, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect("keeps a nested subagent's launch in order while the root turn is idle", () => - Effect.scoped( + const makeSubagentAssistantFrames = (input: { + readonly parentToolUseId: string; + readonly uuid: string; + readonly messageId?: string; + readonly text?: string; + readonly bashToolUseId?: string; + }): ReadonlyArray => + [ + ...(input.text === undefined ? [] : [{ type: "text", text: input.text }]), + ...(input.bashToolUseId === undefined + ? [] + : [ + { + type: "tool_use", + id: input.bashToolUseId, + name: "Bash", + input: { command: "git log -5" }, + }, + ]), + ].map((block, index) => + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: input.messageId ?? `msg_${input.uuid}`, + type: "message", + role: "assistant", + content: [block], + }, + parent_tool_use_id: input.parentToolUseId, + uuid: index === 0 ? input.uuid : `${input.uuid}:${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + const makeSubagentToolResultFrame = (input: { + readonly parentToolUseId: string; + readonly uuid: string; + readonly toolUseId: string; + }) => + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [{ type: "tool_result", tool_use_id: input.toolUseId, content: "ok" }], + }, + parent_tool_use_id: input.parentToolUseId, + uuid: input.uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const makeSubagentTaskStartedFrame = (input: { + readonly taskId: string; + readonly toolUseId: string; + readonly uuid: string; + }) => + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: input.taskId, + tool_use_id: input.toolUseId, + description: "Audit recent commits", + subagent_type: "general-purpose", + is_backgrounded: true, + task_type: "local_agent", + prompt: "Audit the last five commits.", + uuid: input.uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const makeSubagentNotificationFrame = (input: { + readonly taskId: string; + readonly toolUseId: string; + readonly summary: string; + readonly uuid: string; + }) => + claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: input.taskId, + tool_use_id: input.toolUseId, + status: "completed", + output_file: `/tmp/${input.taskId}.output`, + summary: input.summary, + uuid: input.uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const subagentRouting = ( + events: ReadonlyArray, + nativeToolIds: ReadonlyArray, + ) => { + const childThreadId = + events.find((event) => event.type === "subagent.updated")?.subagent.childThreadId ?? + undefined; + const toolThreadIds = new Map>(); + for (const event of events) { + const nativeId = + event.type === "turn_item.updated" ? event.turnItem.nativeItemRef?.nativeId : undefined; + if (event.type === "turn_item.updated" && nativeId && nativeToolIds.includes(nativeId)) { + toolThreadIds.set( + nativeId, + (toolThreadIds.get(nativeId) ?? new Set()).add(event.turnItem.threadId), + ); + } + } + const assistantTexts = (threadId: string | undefined) => + events.flatMap((event) => + event.type === "message.updated" && + event.message.role === "assistant" && + event.message.threadId === threadId + ? [event.message.text] + : [], + ); + return { childThreadId, toolThreadIds, assistantTexts }; + }; + + it.effect.each([ + { label: "an empty one", quotaFailureFirst: false }, + { label: "a quota failure and an empty one", quotaFailureFirst: true }, + ])( + "keeps the wake run open for the turn Claude opens right after $label", + ({ quotaFailureFirst }) => Effect.gen(function* () { - const OUTER_TASK_ID = "task-idle-outer"; - const OUTER_TOOL_USE_ID = "toolu-idle-outer"; - const NESTED_TASK_ID = "task-idle-nested"; - const NESTED_TOOL_USE_ID = "toolu-idle-nested"; const harness = yield* makeWakeHarness; const now = yield* DateTime.now; + const subagents = [ + { taskId: "task-wake-pair-a", toolUseId: "toolu_wake_pair_a" }, + { taskId: "task-wake-pair-b", toolUseId: "toolu_wake_pair_b" }, + ]; + const wakeAttempt = RunAttemptId.make("attempt-claude-wake-pair-2"); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-idle-nested-1"), - text: "Audit in the background.", + attemptId: RunAttemptId.make("attempt-claude-wake-pair-1"), + text: "Audit both in the background.", attachments: [], }), ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000971", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000972", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); + for (const [index, subagent] of subagents.entries()) { + yield* Queue.offer( + harness.sdkMessages, + makeSubagentTaskStartedFrame({ + ...subagent, + uuid: `00000000-0000-4000-8000-00000000095${index}`, + }), + ); } + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000952", result: "Started." }), + ); yield* harness.awaitTerminal(1); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_idle_nested_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: NESTED_TOOL_USE_ID, - name: "Agent", - input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, - }, - ], - }, - parent_tool_use_id: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000973", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: NESTED_TASK_ID, - tool_use_id: NESTED_TOOL_USE_ID, - description: "Nested check", - subagent_type: "general-purpose", - is_backgrounded: false, - spawn_depth: 2, - task_type: "local_agent", - prompt: "Reply with NESTED_OK", - uuid: "00000000-0000-4000-8000-000000000974", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: OUTER_TASK_ID, - description: "Waiting on the nested check", - uuid: "00000000-0000-4000-8000-000000000984", - session_id: WAKE_NATIVE_SESSION, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000988", - messageId: "msg_idle_outer_working", - text: "OUTER_WORKING", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.until(() => - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === "OUTER_WORKING", - ), - ); - assert.lengthOf(harness.continuationRequests, 0); - for (const frame of [ - ...makeSubagentAssistantFrames({ - parentToolUseId: NESTED_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000975", - text: "NESTED_OK", - }), - makeSubagentNotificationFrame({ - taskId: NESTED_TASK_ID, - toolUseId: NESTED_TOOL_USE_ID, - summary: "NESTED_OK", - uuid: "00000000-0000-4000-8000-000000000976", - }), - makeSubagentToolResultFrame({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000977", - toolUseId: NESTED_TOOL_USE_ID, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000978", - text: "OUTER_DONE", - }), - makeSubagentNotificationFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - summary: "OUTER_DONE", - uuid: "00000000-0000-4000-8000-000000000979", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); + // Both subagents end together. Claude runs an empty turn for the first + // notification and opens the real one a millisecond later, all before + // the wake run attaches. + for (const [index, subagent] of subagents.entries()) { + yield* Queue.offer( + harness.sdkMessages, + makeSubagentNotificationFrame({ + ...subagent, + summary: "AUDITED", + uuid: `00000000-0000-4000-8000-00000000096${index}`, + }), + ); } - yield* harness.awaitContinuation(1); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.progress === "Waiting on the nested check", - ), - ); + // A rejected wake that precedes the empty turn still must not settle + // the run the live turn owns. + if (quotaFailureFirst) { + yield* harness.offerAndWait( + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000964", + error: "rate_limit", + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000965", + result: "You've hit your session limit · resets 11:10am (Australia/Sydney)", + isError: true, + apiErrorStatus: 429, + terminalReason: "api_error", + origin: { kind: "task-notification" }, + }), + ); + } + yield* Queue.offer(harness.sdkMessages, wakeTurnInit); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000980", - result: "The audit finished.", + uuid: "00000000-0000-4000-8000-000000000962", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, }), ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000963" }), + ); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-idle-nested-2"), + attemptId: wakeAttempt, text: "Background task completed.", attachments: [], providerTurnOrdinal: 2, @@ -16722,31 +15922,23 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* harness.awaitTerminal(2); + // Claude is still thinking, so the run stays working rather than + // settling with nothing to show. + assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse( + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.awaitTerminal(2); + assert.equal(harness.terminalEvents()[1]?.status, "completed"); + assert.lengthOf(harness.continuationRequests, 1); + assert.isTrue( harness.events.some( (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === NESTED_TOOL_USE_ID, - ), - ); - const finalSubagents = new Map( - harness.events.flatMap((event) => - event.type === "subagent.updated" - ? [[event.subagent.nativeTaskRef?.nativeId, event.subagent] as const] - : [], + event.type === "message.updated" && + event.message.runId === RunId.make(`run-${wakeAttempt}`) && + event.message.text === WAKE_RESULT_TEXT, ), ); - const outer = finalSubagents.get(OUTER_TASK_ID); - const nested = finalSubagents.get(NESTED_TASK_ID); - assert.equal(outer?.status, "completed"); - assert.equal(nested?.status, "completed"); - assert.equal(nested?.parentNodeId, outer?.id); - assert.deepEqual( - subagentRouting(harness.events, []).assistantTexts(outer?.childThreadId ?? undefined), - ["OUTER_WORKING", "OUTER_DONE"], - ); }).pipe( Effect.provide( Layer.mergeAll( @@ -16757,995 +15949,1416 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect("ends an earlier turn's nested subagent while the root turn is idle", () => - Effect.scoped( - Effect.gen(function* () { - const OUTER_TASK_ID = "task-earlier-outer"; - const OUTER_TOOL_USE_ID = "toolu-earlier-outer"; - const NESTED_TASK_ID = "task-earlier-nested"; - const NESTED_TOOL_USE_ID = "toolu-earlier-nested"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const userTurn = (attemptId: string, providerTurnOrdinal: number) => - harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(attemptId), - text: "Keep auditing.", - attachments: [], - providerTurnOrdinal, + // A Stop closes the first process, and a turn replaces it before its stream ends. + const stopRacedByReplacementTurn = (label: string) => + Effect.gen(function* () { + const changes = yield* makeChangeSignal; + const fileSystem = yield* FileSystem.FileSystem; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: `t3-claude-v2-${label}-`, + }); + const processQueues: Array> = []; + // The first two processes exit only when the test ends their streams. + const closeRequested = [yield* Deferred.make(), yield* Deferred.make()]; + const events: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + continuationRequests: { offer: () => Effect.void }, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + const closeSignal = closeRequested[processQueues.length]; + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => Effect.void, + mcpServerStatus: Effect.die("unexpected MCP server status"), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + interrupt: Effect.void, + close: + closeSignal === undefined + ? Queue.shutdown(sdkMessages) + : Deferred.succeed(closeSignal, undefined).pipe(Effect.asVoid), + }; }), - ); - yield* userTurn("attempt-claude-earlier-nested-1", 1); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a01", - }), - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_earlier_nested_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: NESTED_TOOL_USE_ID, - name: "Agent", - input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, - }, - ], - }, - parent_tool_use_id: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a02", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: NESTED_TASK_ID, - tool_use_id: NESTED_TOOL_USE_ID, - description: "Nested check", - subagent_type: "general-purpose", - is_backgrounded: false, - spawn_depth: 2, - task_type: "local_agent", - prompt: "Reply with NESTED_OK", - uuid: "00000000-0000-4000-8000-000000000a03", - session_id: WAKE_NATIVE_SESSION, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000a04", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - yield* userTurn("attempt-claude-earlier-nested-2", 2); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a05", result: "Still on it." }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make(`thread-claude-${label}`); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`provider-session-claude-${label}`), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + const terminals = () => events.filter((event) => event.type === "turn.terminal"); + const subagentStatus = (taskId: string) => { + const latest = events.findLast( + (event) => + event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === taskId, ); - yield* harness.awaitTerminal(2); + return latest?.type === "subagent.updated" ? latest.subagent.status : undefined; + }; + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make(`attempt-claude-${label}-a`), + text: "Audit the last commits in the background.", + attachments: [], + }), + ); + yield* Queue.offer( + processQueues[0]!, + makeSubagentTaskStartedFrame({ + taskId: "raced-agent", + toolUseId: "toolu-raced-agent", + uuid: "00000000-0000-4000-8000-000000002801", + }), + ); + yield* Queue.offer( + processQueues[0]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002802", + result: "Launched the audit.", + }), + ); + yield* changes.until( + () => terminals().length === 1 && subagentStatus("raced-agent") === "running", + ); + + const stop = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: terminals()[0]!.providerTurnId, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(closeRequested[0]!); + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make(`attempt-claude-${label}-b`), + text: "Resume after the limit reset.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + assert.lengthOf(processQueues, 2); + yield* Queue.offer( + processQueues[1]!, + makeSubagentTaskStartedFrame({ + taskId: "own-agent", + toolUseId: "toolu-own-agent", + uuid: "00000000-0000-4000-8000-000000002804", + }), + ); + yield* changes.until(() => subagentStatus("own-agent") === "running"); + const exitProcess = (index: number, stopping: Fiber.Fiber) => + Queue.shutdown(processQueues[index]!).pipe(Effect.andThen(Fiber.join(stopping))); + return { + runtime, + threadId, + providerThread, + processQueues, + closeRequested, + changes, + terminals, + subagentStatus, + exitFirstProcess: exitProcess(0, stop), + exitProcess, + now, + }; + }); + + // regression: #28331 a subagent whose process is gone must not stay running forever + it.effect("ends a subagent whose process a Stop closed while a new turn replaced it", () => + Effect.gen(function* () { + const { processQueues, changes, terminals, subagentStatus, exitFirstProcess } = + yield* stopRacedByReplacementTurn("raced-stop-replacement-close"); + yield* exitFirstProcess; + // The replacement's result follows the stopped process's exit on the event stream. + yield* Queue.offer( + processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000002803", + result: "Resumed.", + }), + ); + yield* changes.until(() => terminals().length === 2); - for (const frame of [ - makeSubagentNotificationFrame({ - taskId: NESTED_TASK_ID, - toolUseId: NESTED_TOOL_USE_ID, - summary: "NESTED_OK", - uuid: "00000000-0000-4000-8000-000000000a06", - }), - makeSubagentToolResultFrame({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a07", - toolUseId: NESTED_TOOL_USE_ID, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a08", - text: "OUTER_AFTER_NESTED", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED", - ), - ); + assert.strictEqual( + subagentStatus("raced-agent"), + "cancelled", + "the Stop ended the subagent's process, but the subagent is not cancelled", + ); + assert.strictEqual( + subagentStatus("own-agent"), + "running", + "the replacement process still runs its own subagent", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - assert.isFalse( - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === NESTED_TOOL_USE_ID, - ), - ); - const nested = harness.events.findLast( - (event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID, - ); - assert.equal(nested?.type === "subagent.updated" && nested.subagent.status, "completed"); - assert.lengthOf(harness.continuationRequests, 0); + // regression: #28331 Stop must clear a subagent whose process is gone + it.effect("stops a subagent whose process a Stop closed while a new turn replaced it", () => + Effect.gen(function* () { + const { runtime, providerThread, exitFirstProcess } = yield* stopRacedByReplacementTurn( + "raced-stop-replacement-stop-subagent", + ); + yield* exitFirstProcess; + const stopped = yield* runtime.stopSubagent!({ + providerThread: { ...providerThread, status: "active" }, + nativeTaskId: "raced-agent", }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.map((outcome) => outcome?.status ?? "no outcome"), + Effect.catch((error) => + Effect.succeed(`refused: ${"detail" in error ? error.detail : error.message}`), + ), + ); + + assert.strictEqual(stopped, "cancelled", "Stop of a subagent whose process is gone"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("keeps an idle-launched nested subagent completed through a sibling's wake", () => - Effect.scoped( - Effect.gen(function* () { - const OUTER_TASK_ID = "task-16355-outer"; - const OUTER_TOOL_USE_ID = "toolu-16355-outer"; - const NESTED_TASK_ID = "task-16355-nested"; - const NESTED_TOOL_USE_ID = "toolu-16355-nested"; - const SIBLING_TASK_ID = "task-16355-sibling"; - const SIBLING_TOOL_USE_ID = "toolu-16355-sibling"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const nestedStatuses = () => - harness.events.flatMap((event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID - ? [event.subagent.status] - : [], - ); - yield* harness.runtime.startTurn( + // regression: #28331 a process that exits late ends only the subagents it ran + it.effect("leaves a stopping replacement's subagent to that replacement's exit", () => + Effect.gen(function* () { + const { + runtime, + threadId, + providerThread, + processQueues, + closeRequested, + changes, + terminals, + subagentStatus, + exitFirstProcess, + exitProcess, + now, + } = yield* stopRacedByReplacementTurn("raced-stop-replacement-chain"); + const activeThread = { ...providerThread, status: "active" as const }; + const finishTurn = (index: number, turns: number, uuid: string) => + Queue.offer(processQueues[index]!, makeResultFrame({ uuid, result: "Done." })).pipe( + Effect.andThen(changes.until(() => terminals().length === turns)), + ); + const startTurn = (label: string, providerTurnOrdinal: number) => + runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, + threadId, + providerThread: activeThread, now, - attemptId: RunAttemptId.make("attempt-claude-16355-1"), - text: "Run two audits in the background.", + attemptId: RunAttemptId.make(`attempt-claude-raced-stop-replacement-chain-${label}`), + text: "Carry on.", attachments: [], + providerTurnOrdinal, }), ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000016301", - }), - makeSubagentTaskStartedFrame({ - taskId: SIBLING_TASK_ID, - toolUseId: SIBLING_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000016302", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000016303", - result: "Both audits run in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - // The background subagent launches a foreground nested one while the root is idle. - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_16355_nested_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: NESTED_TOOL_USE_ID, - name: "Agent", - input: { description: "Nested check", prompt: "Sleep, then reply NESTED_OK" }, - }, - ], - }, - parent_tool_use_id: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000016304", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: NESTED_TASK_ID, - tool_use_id: NESTED_TOOL_USE_ID, - description: "Nested check", - subagent_type: "general-purpose", - is_backgrounded: false, - spawn_depth: 2, - task_type: "local_agent", - prompt: "Sleep, then reply NESTED_OK", - uuid: "00000000-0000-4000-8000-000000016305", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: NESTED_TASK_ID, - description: "Sleeping", - uuid: "00000000-0000-4000-8000-000000016306", - session_id: WAKE_NATIVE_SESSION, - }), - ]) { - yield* harness.offerAndWait(frame); - } + yield* finishTurn(1, 2, "00000000-0000-4000-8000-000000002805"); + const stopSecond = yield* runtime + .interruptTurn({ + providerThread: activeThread, + providerTurnId: terminals()[1]!.providerTurnId, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(closeRequested[1]!); + yield* startTurn("c", 3); + assert.lengthOf(processQueues, 3); + + yield* exitFirstProcess; + yield* finishTurn(2, 3, "00000000-0000-4000-8000-000000002806"); + assert.strictEqual( + subagentStatus("raced-agent"), + "cancelled", + "the first process exited after a Stop, but its subagent is not cancelled", + ); + assert.strictEqual( + subagentStatus("own-agent"), + "running", + "the first process ended a subagent the second process still ran", + ); - // A user turn runs while the nested and then the outer subagent finish. - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-16355-2"), - text: "Sleep for a while.", - attachments: [], - providerTurnOrdinal: 2, - }), + yield* exitProcess(1, stopSecond); + yield* startTurn("d", 4); + yield* finishTurn(2, 4, "00000000-0000-4000-8000-000000002807"); + assert.strictEqual( + subagentStatus("own-agent"), + "cancelled", + "the second process exited after a Stop, but its subagent is not cancelled", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("streams a background subagent's work while the root turn is idle", () => + Effect.gen(function* () { + const TASK_ID = "task-live-idle"; + const TOOL_USE_ID = "toolu-live-idle"; + const STRADDLING_BASH = "toolu-live-straddling-bash"; + const IDLE_BASH = "toolu-live-idle-bash"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const latestToolItem = (nativeId: string) => + harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, ); - yield* harness.until(() => harness.offeredMessages.length === 2); - for (const frame of [ - makeSubagentNotificationFrame({ - taskId: NESTED_TASK_ID, - toolUseId: NESTED_TOOL_USE_ID, - summary: "NESTED_OK", - uuid: "00000000-0000-4000-8000-000000016307", - }), - makeSubagentToolResultFrame({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000016308", - toolUseId: NESTED_TOOL_USE_ID, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000016309", - text: "OUTER_DONE", - }), - makeSubagentNotificationFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - summary: "OUTER_DONE", - uuid: "00000000-0000-4000-8000-000000016310", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000016311", - result: "Slept.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(2); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-live-idle-1"), + text: "Audit in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000951", + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000952", + bashToolUseId: STRADDLING_BASH, + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000953", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + for (const frame of [ + makeSubagentToolResultFrame({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000954", + toolUseId: STRADDLING_BASH, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000955", + text: "Still auditing.", + bashToolUseId: IDLE_BASH, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: TASK_ID, + description: "Reading the last commits", + uuid: "00000000-0000-4000-8000-000000000956", + session_id: WAKE_NATIVE_SESSION, + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.until(() => { + const event = latestToolItem(IDLE_BASH); + return event?.type === "turn_item.updated" && event.turnItem.status === "running"; + }); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "subagent.updated" && + event.subagent.progress === "Reading the last commits", + ), + ); + const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]); + assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]); + const straddling = latestToolItem(STRADDLING_BASH); + const straddlingItem = + straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined; + assert.equal(straddlingItem?.status, "completed"); + assert.equal( + straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined, + "git log -5", + ); + assert.equal(harness.continuationRequests.length, 0); + + for (const frame of [ + makeSubagentToolResultFrame({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000957", + toolUseId: IDLE_BASH, + }), + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + summary: "Still auditing.", + uuid: "00000000-0000-4000-8000-000000000958", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000959", + result: "The auditor finished.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-live-idle-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(2); - // The sibling's completion wakes a continuation while the root is idle. - for (const frame of [ - makeSubagentNotificationFrame({ - taskId: SIBLING_TASK_ID, - toolUseId: SIBLING_TOOL_USE_ID, - summary: "SIBLING_DONE", - uuid: "00000000-0000-4000-8000-000000016312", - }), - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000016313", - text: "Both audits finished.", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000016314", - result: "Both audits finished.", - origin: { kind: "task-notification" }, - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitContinuation(1); - yield* harness.runtime.startTurn( + const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]); + assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [ + "Still auditing.", + ]); + for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) { + assert.deepEqual( + [...(finalRouting.toolThreadIds.get(nativeId) ?? [])], + [finalRouting.childThreadId], + ); + const statuses = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === nativeId + ? [`${event.turnItem.type}:${event.turnItem.status}`] + : [], + ); + assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]); + } + const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated"); + assert.equal( + finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status, + "completed", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + // Claude reports a background subagent `completed` when its turn ends while + // its own background shell still runs. When that shell finishes, Claude + // resumes the subagent with a new task_started for the same task and launch + // tool_use_id while the root is idle. Frame order mirrors a live capture. + it.effect("reopens a completed background subagent that resumes while the root is idle", () => + Effect.gen(function* () { + const TASK_ID = "ae3f32459af762a5f"; + const LAUNCH = "toolu_01LcidmwEK1Y6GC6LpX3kvxX"; + const OWN_SHELL = "toolu_01QAahgijM2KRBBSkWxnui4g"; + const RESUMED_BASH = "toolu_01CkA1juicPNCtQrqKL8h6Rz"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + let sequence = 0; + const system = (frame: object) => + claudeSdkFrame({ + type: "system", + ...frame, + uuid: `00000000-0000-4000-8000-0000000162${String(++sequence).padStart(2, "0")}`, + session_id: WAKE_NATIVE_SESSION, + }); + const agentEntry = (runId: string) => ({ + task_id: TASK_ID, + run_id: runId, + task_type: "local_agent", + subagent_type: "general-purpose", + description: "Audit recent commits", + }); + const shellEntry = (taskId: string) => ({ + task_id: taskId, + run_id: `run-${taskId}`, + task_type: "local_bash", + description: "Sleep", + parent_task_id: TASK_ID, + }); + const roster = (tasks: ReadonlyArray) => + system({ subtype: "background_tasks_changed", tasks }); + const shellStarted = (taskId: string, toolUseId: string) => + system({ + subtype: "task_started", + task_id: taskId, + tool_use_id: toolUseId, + task_type: "local_bash", + description: "Sleep", + }); + const startTurn = (ordinal: number, continuation: boolean) => + harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-16355-3"), - text: "Background task completed.", + attemptId: RunAttemptId.make(`attempt-claude-self-resume-${ordinal}`), + text: continuation ? "Background task completed." : "Launch a background agent.", attachments: [], - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", + providerTurnOrdinal: ordinal, + ...(continuation + ? { + messageCreatedBy: "agent" as const, + messageCreationSource: "provider" as const, + } + : {}), }), ); - yield* harness.awaitTerminal(3); + const subagentUpdates = () => + harness.events.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent] : [], + ); - assert.equal(nestedStatuses().at(-1), "completed"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* startTurn(1, false); + for (const frame of [ + roster([agentEntry("run-1")]), + makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016101", + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000016102", result: "LAUNCHED" }), + ]) { + yield* harness.offerAndWait(frame); + } + yield* Queue.take(harness.terminalReceipts); + + // The subagent starts its own background shell, ends its turn, and + // Claude reports it completed; the parent wakes, answers, goes idle. + for (const frame of [ + ...makeSubagentAssistantFrames({ + parentToolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016103", + bashToolUseId: OWN_SHELL, + }), + roster([agentEntry("run-1"), shellEntry("b455x9pq5")]), + shellStarted("b455x9pq5", OWN_SHELL), + makeSubagentToolResultFrame({ + parentToolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016104", + toolUseId: OWN_SHELL, + }), + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + summary: "WAITING", + uuid: "00000000-0000-4000-8000-000000016105", + }), + roster([shellEntry("b455x9pq5")]), + wakeTurnInit, + ]) { + yield* harness.offerAndWait(frame); + } + yield* Queue.take(harness.continuationReceipts); + yield* startTurn(2, true); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000016106", result: "Noted." }), + ); + yield* Queue.take(harness.terminalReceipts); + + // Its shell finishes and Claude resumes it under a new native run. + for (const frame of [ + system({ + subtype: "task_notification", + task_id: "b455x9pq5", + tool_use_id: OWN_SHELL, + status: "completed", + summary: "Background command completed (exit code 0)", + output_file: "/tmp/b455x9pq5.output", + }), + roster([]), + roster([agentEntry("run-2")]), + makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016107", + }), + ]) { + yield* harness.offerAndWait(frame); + } + // Events reach the app only through a run, and the launching run ended + // with the interim completion. + assert.equal(harness.continuationRequests.length, 2); + + yield* Queue.take(harness.continuationReceipts); + yield* startTurn(3, true); + // Claude does not wake the root for this, so the root must not stay busy. + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + yield* startTurn(4, false); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000016110", result: "PONG" }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + for (const frame of [ + ...makeSubagentAssistantFrames({ + parentToolUseId: LAUNCH, + uuid: "00000000-0000-4000-8000-000000016108", + bashToolUseId: RESUMED_BASH, + }), + shellStarted("beyhxkdpc", RESUMED_BASH), + roster([agentEntry("run-2"), shellEntry("beyhxkdpc")]), + ]) { + yield* harness.offerAndWait(frame); + } + // Events are ordered: once this roster is recorded, so is every earlier event. + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.pendingBackgroundTasks?.some( + (task) => task.taskId === "beyhxkdpc", + ) === true, + ), + ); + const resumed = subagentUpdates().at(-1); + assert.equal(resumed?.status, "running"); + assert.isNull(resumed?.completedAt); + assert.equal(resumed?.runId, "run-attempt-claude-self-resume-3"); + const routing = subagentRouting(harness.events, [RESUMED_BASH]); + assert.deepEqual( + [...(routing.toolThreadIds.get(RESUMED_BASH) ?? [])], + [routing.childThreadId], + ); + + yield* harness.offerAndWait( + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: LAUNCH, + summary: "DONE", + uuid: "00000000-0000-4000-8000-000000016109", + }), + ); + yield* harness.until(() => subagentUpdates().at(-1)?.result === "DONE"); + assert.equal(subagentUpdates().at(-1)?.status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect.each(["exit", "Stop"] as const)( - "settles a plain background subagent and its open call on %s after the root turn completes", - (reason) => - Effect.scoped( - Effect.gen(function* () { - const TOOL_USE_ID = "toolu-idle-exit"; - const BASH = "toolu-idle-exit-bash"; - const harness = yield* makeWakeHarnessWithOptions({ close: Queue.shutdown }); - const now = yield* DateTime.now; - const bashStatuses = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH - ? [`${event.turnItem.type}:${event.turnItem.status}`] - : [], - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-idle-exit"), - text: "Audit in the background.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - makeSubagentTaskStartedFrame({ - taskId: "task-idle-exit", - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000981", - }), - ); - const started = yield* Queue.take(harness.subagentReceipts); - assert.equal(started.subagent.status, "running"); - for (const frame of makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000982", - bashToolUseId: BASH, - })) { - yield* harness.offerAndWait(frame); - } - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000983", - result: "Auditing in the background.", - }), - ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "completed"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - assert.deepEqual(bashStatuses(), ["command_execution:running"]); + it.effect("keeps a nested subagent's launch in order while the root turn is idle", () => + Effect.gen(function* () { + const OUTER_TASK_ID = "task-idle-outer"; + const OUTER_TOOL_USE_ID = "toolu-idle-outer"; + const NESTED_TASK_ID = "task-idle-nested"; + const NESTED_TOOL_USE_ID = "toolu-idle-nested"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-idle-nested-1"), + text: "Audit in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000971", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000972", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); - if (reason === "Stop") { - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: terminal.providerTurnId, - requestRuntimeRestart: true, - }); - } else { - yield* Queue.shutdown(harness.sdkMessages); - } - let ended = yield* Queue.take(harness.subagentReceipts); - while (ended.subagent.status === "running") { - ended = yield* Queue.take(harness.subagentReceipts); - } - assert.equal(ended.subagent.nativeTaskRef?.nativeId, "task-idle-exit"); - assert.equal(ended.subagent.status, reason === "Stop" ? "cancelled" : "failed"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.deepEqual(bashStatuses(), [ - "command_execution:running", - reason === "Stop" ? "command_execution:interrupted" : "command_execution:failed", - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_idle_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, + }, + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000973", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Reply with NESTED_OK", + uuid: "00000000-0000-4000-8000-000000000974", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: OUTER_TASK_ID, + description: "Waiting on the nested check", + uuid: "00000000-0000-4000-8000-000000000984", + session_id: WAKE_NATIVE_SESSION, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000988", + messageId: "msg_idle_outer_working", + text: "OUTER_WORKING", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.until(() => + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === "OUTER_WORKING", + ), + ); + assert.lengthOf(harness.continuationRequests, 0); + for (const frame of [ + ...makeSubagentAssistantFrames({ + parentToolUseId: NESTED_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000975", + text: "NESTED_OK", + }), + makeSubagentNotificationFrame({ + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000000976", + }), + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000977", + toolUseId: NESTED_TOOL_USE_ID, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000978", + text: "OUTER_DONE", + }), + makeSubagentNotificationFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + summary: "OUTER_DONE", + uuid: "00000000-0000-4000-8000-000000000979", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "subagent.updated" && + event.subagent.progress === "Waiting on the nested check", + ), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000980", + result: "The audit finished.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-idle-nested-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(2); + + assert.isFalse( + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === NESTED_TOOL_USE_ID, + ), + ); + const finalSubagents = new Map( + harness.events.flatMap((event) => + event.type === "subagent.updated" + ? [[event.subagent.nativeTaskRef?.nativeId, event.subagent] as const] + : [], + ), + ); + const outer = finalSubagents.get(OUTER_TASK_ID); + const nested = finalSubagents.get(NESTED_TASK_ID); + assert.equal(outer?.status, "completed"); + assert.equal(nested?.status, "completed"); + assert.equal(nested?.parentNodeId, outer?.id); + assert.deepEqual( + subagentRouting(harness.events, []).assistantTexts(outer?.childThreadId ?? undefined), + ["OUTER_WORKING", "OUTER_DONE"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect.each(["before", "after"] as const)( - "keeps a subagent call's result when the CLI exits before the drain (result %s the nested launch's)", - (bashResultOrder) => - Effect.scoped( - Effect.gen(function* () { - const OUTER_TASK_ID = "task-exit-buffered-outer"; - const OUTER_TOOL_USE_ID = "toolu-exit-buffered-outer"; - const NESTED_TASK_ID = "task-exit-buffered-nested"; - const NESTED_TOOL_USE_ID = "toolu-exit-buffered-nested"; - const BASH = "toolu-exit-buffered-bash"; - const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); - const now = yield* DateTime.now; - const bashItems = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH - ? [ - `${event.turnItem.type}:${event.turnItem.status}:${JSON.stringify("input" in event.turnItem ? event.turnItem.input : null)}`, - ] - : [], - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-exit-buffered-1"), - text: "Audit in the background.", - attachments: [], - }), - ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001001", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001002", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - - for (const frame of makeSubagentAssistantFrames({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001003", - bashToolUseId: BASH, - })) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.until(() => bashItems().length === 1); - - const bashResultFrame = makeSubagentToolResultFrame({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001006", - toolUseId: BASH, - }); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_exit_buffered_nested_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: NESTED_TOOL_USE_ID, - name: "Agent", - input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, - }, - ], + it.effect("ends an earlier turn's nested subagent while the root turn is idle", () => + Effect.gen(function* () { + const OUTER_TASK_ID = "task-earlier-outer"; + const OUTER_TOOL_USE_ID = "toolu-earlier-outer"; + const NESTED_TASK_ID = "task-earlier-nested"; + const NESTED_TOOL_USE_ID = "toolu-earlier-nested"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const userTurn = (attemptId: string, providerTurnOrdinal: number) => + harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(attemptId), + text: "Keep auditing.", + attachments: [], + providerTurnOrdinal, + }), + ); + yield* userTurn("attempt-claude-earlier-nested-1", 1); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a01", + }), + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_earlier_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, }, - parent_tool_use_id: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001004", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: NESTED_TASK_ID, - tool_use_id: NESTED_TOOL_USE_ID, - description: "Nested check", - subagent_type: "general-purpose", - is_backgrounded: false, - spawn_depth: 2, - task_type: "local_agent", - prompt: "Reply with NESTED_OK", - uuid: "00000000-0000-4000-8000-000000001005", - session_id: WAKE_NATIVE_SESSION, - }), - ...(bashResultOrder === "before" ? [bashResultFrame] : []), - ...makeSubagentAssistantFrames({ - parentToolUseId: NESTED_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001007", - text: "NESTED_OK", - }), - makeSubagentNotificationFrame({ - taskId: NESTED_TASK_ID, - toolUseId: NESTED_TOOL_USE_ID, - summary: "NESTED_OK", - uuid: "00000000-0000-4000-8000-000000001008", - }), - makeSubagentToolResultFrame({ - parentToolUseId: OUTER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001009", - toolUseId: NESTED_TOOL_USE_ID, - }), - ...(bashResultOrder === "after" ? [bashResultFrame] : []), - makeSubagentNotificationFrame({ - taskId: OUTER_TASK_ID, - toolUseId: OUTER_TOOL_USE_ID, - summary: "OUTER_DONE", - uuid: "00000000-0000-4000-8000-000000001010", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitContinuation(1); - - yield* Queue.shutdown(harness.sdkMessages); - yield* yieldTicks(50); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-exit-buffered-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - assert.equal(harness.processQueues.length, 2); - yield* Queue.offer( - harness.processQueues[1]!, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001011", - result: "The audit finished.", - }), - ); - yield* harness.awaitTerminal(2); + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a02", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Reply with NESTED_OK", + uuid: "00000000-0000-4000-8000-000000000a03", + session_id: WAKE_NATIVE_SESSION, + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a04", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + yield* userTurn("attempt-claude-earlier-nested-2", 2); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a05", result: "Still on it." }), + ); + yield* harness.awaitTerminal(2); + + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000000a06", + }), + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a07", + toolUseId: NESTED_TOOL_USE_ID, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a08", + text: "OUTER_AFTER_NESTED", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED", + ), + ); - const input = JSON.stringify("git log -5"); - assert.deepEqual(bashItems(), [ - `command_execution:running:${input}`, - `command_execution:completed:${input}`, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + assert.isFalse( + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === NESTED_TOOL_USE_ID, + ), + ); + const nested = harness.events.findLast( + (event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID, + ); + assert.equal(nested?.type === "subagent.updated" && nested.subagent.status, "completed"); + assert.lengthOf(harness.continuationRequests, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect( - "ends a subagent's SendMessage with its result when the CLI exits while the resume waits", - () => - Effect.scoped( - Effect.gen(function* () { - const SENDER_TASK_ID = "task-exit-resume-sender"; - const SENDER_TOOL_USE_ID = "toolu-exit-resume-sender"; - const RESUMED_TASK_ID = "task-exit-resume-target"; - const RESUMED_TOOL_USE_ID = "toolu-exit-resume-target"; - const SEND = "toolu-exit-resume-sendmessage"; - const SEND_INPUT = { to: RESUMED_TASK_ID, message: "Check the last commit again." }; - const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); - const now = yield* DateTime.now; - const sendItems = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === SEND - ? [ - `${event.turnItem.type}:${event.turnItem.status}:${JSON.stringify("input" in event.turnItem ? event.turnItem.input : null)}`, - ] - : [], - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-exit-resume-1"), - text: "Run two auditors in the background.", - attachments: [], - }), - ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: SENDER_TASK_ID, - toolUseId: SENDER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001101", - }), - makeSubagentTaskStartedFrame({ - taskId: RESUMED_TASK_ID, - toolUseId: RESUMED_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001102", - }), - makeSubagentNotificationFrame({ - taskId: RESUMED_TASK_ID, - toolUseId: RESUMED_TOOL_USE_ID, - summary: "First answer.", - uuid: "00000000-0000-4000-8000-000000001103", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001104", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); - - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_exit_resume_sendmessage", - type: "message", - role: "assistant", - content: [{ type: "tool_use", id: SEND, name: "SendMessage", input: SEND_INPUT }], - }, - parent_tool_use_id: SENDER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001105", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.until(() => sendItems().length >= 1); + it.effect("keeps an idle-launched nested subagent completed through a sibling's wake", () => + Effect.gen(function* () { + const OUTER_TASK_ID = "task-16355-outer"; + const OUTER_TOOL_USE_ID = "toolu-16355-outer"; + const NESTED_TASK_ID = "task-16355-nested"; + const NESTED_TOOL_USE_ID = "toolu-16355-nested"; + const SIBLING_TASK_ID = "task-16355-sibling"; + const SIBLING_TOOL_USE_ID = "toolu-16355-sibling"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const nestedStatuses = () => + harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === NESTED_TASK_ID + ? [event.subagent.status] + : [], + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-1"), + text: "Run two audits in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016301", + }), + makeSubagentTaskStartedFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016302", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016303", + result: "Both audits run in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); - for (const frame of [ - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: RESUMED_TASK_ID, - tool_use_id: SEND, - description: "Audit recent commits", - is_backgrounded: true, - task_type: "local_agent", - prompt: SEND_INPUT.message, - uuid: "00000000-0000-4000-8000-000000001106", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [{ type: "tool_result", tool_use_id: SEND, content: "Message sent." }], + // The background subagent launches a foreground nested one while the root is idle. + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_16355_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Sleep, then reply NESTED_OK" }, }, - parent_tool_use_id: SENDER_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001107", - session_id: WAKE_NATIVE_SESSION, - }), - makeSubagentNotificationFrame({ - taskId: RESUMED_TASK_ID, - toolUseId: SEND, - summary: "Second answer.", - uuid: "00000000-0000-4000-8000-000000001108", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitContinuation(1); - const beforeExit = sendItems(); + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016304", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Sleep, then reply NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016305", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: NESTED_TASK_ID, + description: "Sleeping", + uuid: "00000000-0000-4000-8000-000000016306", + session_id: WAKE_NATIVE_SESSION, + }), + ]) { + yield* harness.offerAndWait(frame); + } - yield* Queue.shutdown(harness.sdkMessages); - yield* yieldTicks(50); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-exit-resume-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - assert.equal(harness.processQueues.length, 2); - yield* Queue.offer( - harness.processQueues[1]!, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001109", - result: "The audit finished.", - }), - ); - yield* harness.awaitTerminal(2); + // A user turn runs while the nested and then the outer subagent finish. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-2"), + text: "Sleep for a while.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000016307", + }), + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016308", + toolUseId: NESTED_TOOL_USE_ID, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000016309", + text: "OUTER_DONE", + }), + makeSubagentNotificationFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + summary: "OUTER_DONE", + uuid: "00000000-0000-4000-8000-000000016310", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016311", + result: "Slept.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(2); + + // The sibling's completion wakes a continuation while the root is idle. + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: SIBLING_TASK_ID, + toolUseId: SIBLING_TOOL_USE_ID, + summary: "SIBLING_DONE", + uuid: "00000000-0000-4000-8000-000000016312", + }), + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000016313", + text: "Both audits finished.", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000016314", + result: "Both audits finished.", + origin: { kind: "task-notification" }, + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-16355-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); - const input = JSON.stringify(SEND_INPUT); - assert.deepEqual(beforeExit, [`dynamic_tool:running:${input}`]); - assert.deepEqual(sendItems(), [ - `dynamic_tool:running:${input}`, - `dynamic_tool:completed:${input}`, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + assert.equal(nestedStatuses().at(-1), "completed"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect.each([ - ["", "none"], - [" behind another subagent's start without one", "before"], - [" when another subagent's start without one arrives between its frames", "between"], - ] as const)( - "keeps a subagent's frames in order when a late progress names its tool use while the root is idle%s", - ([, otherStart]) => - Effect.scoped( - Effect.gen(function* () { - const TASK_ID = "task-late-owner-idle"; - const TOOL_USE_ID = "toolu-late-owner-idle"; - const BASH = "toolu-late-owner-idle-bash"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const bashStatuses = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH - ? [`${event.turnItem.type}:${event.turnItem.status}`] - : [], - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-late-owner-idle-1"), - text: "Audit in the background.", - attachments: [], - }), + it.effect.each(["exit", "Stop"] as const)( + "settles a plain background subagent and its open call on %s after the root turn completes", + (reason) => + Effect.gen(function* () { + const TOOL_USE_ID = "toolu-idle-exit"; + const BASH = "toolu-idle-exit-bash"; + const harness = yield* makeWakeHarnessWithOptions({ close: Queue.shutdown }); + const now = yield* DateTime.now; + const bashStatuses = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH + ? [`${event.turnItem.type}:${event.turnItem.status}`] + : [], ); - for (const frame of [ - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: TASK_ID, - description: "Audit recent commits", - subagent_type: "general-purpose", - is_backgrounded: true, - task_type: "local_agent", - prompt: "Audit the last five commits.", - uuid: "00000000-0000-4000-8000-000000000a01", - session_id: WAKE_NATIVE_SESSION, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000a02", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-idle-exit"), + text: "Audit in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + makeSubagentTaskStartedFrame({ + taskId: "task-idle-exit", + toolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000981", + }), + ); + const started = yield* Queue.take(harness.subagentReceipts); + assert.equal(started.subagent.status, "running"); + for (const frame of makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000982", + bashToolUseId: BASH, + })) { + yield* harness.offerAndWait(frame); + } + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000983", + result: "Auditing in the background.", + }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + assert.deepEqual(bashStatuses(), ["command_execution:running"]); - const otherStartFrame = claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: "task-late-owner-other", - description: "Check the changelog", - subagent_type: "general-purpose", - is_backgrounded: true, - task_type: "local_agent", - prompt: "Check the changelog.", - uuid: "00000000-0000-4000-8000-000000000a09", - session_id: WAKE_NATIVE_SESSION, - }); - const progressFrame = claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: TASK_ID, - tool_use_id: TOOL_USE_ID, - description: "Reading the last commits", - usage: { total_tokens: 1, tool_uses: 1, duration_ms: 1 }, - uuid: "00000000-0000-4000-8000-000000000a04", - session_id: WAKE_NATIVE_SESSION, - }); - const bashResultFrame = makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a05", - toolUseId: BASH, + if (reason === "Stop") { + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: terminal.providerTurnId, + requestRuntimeRestart: true, }); - for (const frame of [ - ...(otherStart === "before" ? [otherStartFrame] : []), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a03", - text: "First.", - bashToolUseId: BASH, - }), - ...(otherStart === "between" - ? [otherStartFrame, bashResultFrame, progressFrame] - : [progressFrame, bashResultFrame]), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a06", - text: "Second.", - }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: "Second.", - uuid: "00000000-0000-4000-8000-000000000a07", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitContinuation(1); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000a08", - result: "The auditor finished.", - }), - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-late-owner-idle-2"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.awaitTerminal(2); - - const routing = subagentRouting(harness.events, [BASH]); - const childTexts = routing.assistantTexts(routing.childThreadId); - const statuses = bashStatuses(); - const trace = harness.events.flatMap((event) => - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.threadId === routing.childThreadId - ? [`text:${event.message.text}#${event.message.id}`] - : event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === BASH - ? [`bash:${event.turnItem.status}`] - : [], - ); - assert.deepEqual(childTexts, ["First.", "Second."], `trace: ${JSON.stringify(trace)}`); - assert.deepEqual( - [...(routing.toolThreadIds.get(BASH) ?? [])], - [routing.childThreadId], - `trace: ${JSON.stringify(trace)}`, - ); - assert.deepEqual( - statuses, - ["command_execution:running", "command_execution:completed"], - `trace: ${JSON.stringify(trace)}`, - ); - assert.isTrue( - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.progress === "Reading the last commits", - ), - ); - assert.lengthOf(harness.continuationRequests, 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } else { + yield* Queue.shutdown(harness.sdkMessages); + } + let ended = yield* Queue.take(harness.subagentReceipts); + while (ended.subagent.status === "running") { + ended = yield* Queue.take(harness.subagentReceipts); + } + assert.equal(ended.subagent.nativeTaskRef?.nativeId, "task-idle-exit"); + assert.equal(ended.subagent.status, reason === "Stop" ? "cancelled" : "failed"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.deepEqual(bashStatuses(), [ + "command_execution:running", + reason === "Stop" ? "command_execution:interrupted" : "command_execution:failed", + ]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("holds subagent frames that precede task_started and shows its result once", () => - Effect.scoped( + it.effect.each(["before", "after"] as const)( + "keeps a subagent call's result when the CLI exits before the drain (result %s the nested launch's)", + (bashResultOrder) => Effect.gen(function* () { - const TASK_ID = "task-early-subagent"; - const TOOL_USE_ID = "toolu-early-subagent"; - const FINAL_REPORT = "Early auditor done."; - const harness = yield* makeWakeHarness; + const OUTER_TASK_ID = "task-exit-buffered-outer"; + const OUTER_TOOL_USE_ID = "toolu-exit-buffered-outer"; + const NESTED_TASK_ID = "task-exit-buffered-nested"; + const NESTED_TOOL_USE_ID = "toolu-exit-buffered-nested"; + const BASH = "toolu-exit-buffered-bash"; + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); const now = yield* DateTime.now; + const bashItems = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH + ? [ + `${event.turnItem.type}:${event.turnItem.status}:${JSON.stringify("input" in event.turnItem ? event.turnItem.input : null)}`, + ] + : [], + ); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-early-subagent"), - text: "Run an auditor.", + attemptId: RunAttemptId.make("attempt-claude-exit-buffered-1"), + text: "Audit in the background.", attachments: [], }), ); - const frames = [ - // Child frames can precede the task_started that registers their subagent. - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000321", - text: "Starting early.", - bashToolUseId: "toolu-early-bash", - }), - makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000322", - toolUseId: "toolu-early-bash", - }), + for (const frame of [ makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000323", + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001001", }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000324", - text: "Still working.", + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001002", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + for (const frame of makeSubagentAssistantFrames({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001003", + bashToolUseId: BASH, + })) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.until(() => bashItems().length === 1); + + const bashResultFrame = makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001006", + toolUseId: BASH, + }); + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_exit_buffered_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Reply with NESTED_OK" }, + }, + ], + }, + parent_tool_use_id: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001004", + session_id: WAKE_NATIVE_SESSION, }), claudeSdkFrame({ type: "system", - subtype: "task_progress", - task_id: TASK_ID, - description: "Checking the diffs", - uuid: "00000000-0000-4000-8000-000000000325", + subtype: "task_started", + task_id: NESTED_TASK_ID, + tool_use_id: NESTED_TOOL_USE_ID, + description: "Nested check", + subagent_type: "general-purpose", + is_backgrounded: false, + spawn_depth: 2, + task_type: "local_agent", + prompt: "Reply with NESTED_OK", + uuid: "00000000-0000-4000-8000-000000001005", session_id: WAKE_NATIVE_SESSION, }), + ...(bashResultOrder === "before" ? [bashResultFrame] : []), ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000326", - text: FINAL_REPORT, + parentToolUseId: NESTED_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001007", + text: "NESTED_OK", }), makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: FINAL_REPORT, - uuid: "00000000-0000-4000-8000-000000000327", + taskId: NESTED_TASK_ID, + toolUseId: NESTED_TOOL_USE_ID, + summary: "NESTED_OK", + uuid: "00000000-0000-4000-8000-000000001008", }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000328", - result: "The auditor finished.", + makeSubagentToolResultFrame({ + parentToolUseId: OUTER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001009", + toolUseId: NESTED_TOOL_USE_ID, }), - ]; - for (const frame of frames) { + ...(bashResultOrder === "after" ? [bashResultFrame] : []), + makeSubagentNotificationFrame({ + taskId: OUTER_TASK_ID, + toolUseId: OUTER_TOOL_USE_ID, + summary: "OUTER_DONE", + uuid: "00000000-0000-4000-8000-000000001010", + }), + ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* harness.awaitTerminal(1); + yield* harness.awaitContinuation(1); - const routing = subagentRouting(harness.events, ["toolu-early-bash"]); - assert.isDefined(routing.childThreadId); - // Agents quote this id back to t3_thread_send/t3_thread_read. - const childThreadId = routing.childThreadId ?? ""; - assert.notInclude(childThreadId, "%"); - assert.isAtMost(childThreadId.length, 64); - assert.deepEqual( - [...(routing.toolThreadIds.get("toolu-early-bash") ?? [])], - [routing.childThreadId], + yield* Queue.shutdown(harness.sdkMessages); + yield* yieldTicks(50); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-exit-buffered-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + assert.equal(harness.processQueues.length, 2); + yield* Queue.offer( + harness.processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001011", + result: "The audit finished.", + }), ); - assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ - "Starting early.", - "Still working.", - FINAL_REPORT, + yield* harness.awaitTerminal(2); + + const input = JSON.stringify("git log -5"); + assert.deepEqual(bashItems(), [ + `command_execution:running:${input}`, + `command_execution:completed:${input}`, ]); - assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]); }).pipe( Effect.provide( Layer.mergeAll( @@ -17756,204 +17369,148 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect.each([false, true])( - "drops an idle start superseded by live completion, later resume %s", - (resume) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const startTurn = (ordinal: number, continuation = false) => - harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: DateTime.makeUnsafe(0), - attemptId: RunAttemptId.make(`attempt-stale-start-${ordinal}`), - providerTurnOrdinal: ordinal, - text: "Continue work.", - attachments: [], - ...(continuation - ? { - messageCreatedBy: "agent" as const, - messageCreationSource: "provider" as const, - } - : {}), - }), - ); - const started = (taskId: string, suffix: string) => - makeSubagentTaskStartedFrame({ - taskId, - toolUseId: `toolu-${taskId}`, - uuid: `00000000-0000-4000-8000-${suffix}`, - }); - const finished = (taskId: string, suffix: string) => - makeSubagentNotificationFrame({ - taskId, - toolUseId: `toolu-${taskId}`, - summary: "Finished audit.", - uuid: `00000000-0000-4000-8000-${suffix}`, - }); - yield* startTurn(1); - yield* harness.offerAndWait(started("stale-agent", "000000004001")); - yield* harness.offerAndWait(started("wake-agent", "000000004002")); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000004003", - result: "Agents launched.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait(started("stale-agent", "000000004004")); - yield* startTurn(2); - yield* harness.offerAndWait(finished("stale-agent", "000000004005")); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000004006", - result: "User turn finished.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - if (resume) yield* harness.offerAndWait(started("stale-agent", "000000004007")); - yield* harness.offerAndWait(finished("wake-agent", "000000004008")); - yield* Queue.take(harness.continuationReceipts); - yield* startTurn(3, true); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000004009", - result: "Wake finished.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - const latest = harness.events.findLast( - (event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === "stale-agent", + it.effect( + "ends a subagent's SendMessage with its result when the CLI exits while the resume waits", + () => + Effect.gen(function* () { + const SENDER_TASK_ID = "task-exit-resume-sender"; + const SENDER_TOOL_USE_ID = "toolu-exit-resume-sender"; + const RESUMED_TASK_ID = "task-exit-resume-target"; + const RESUMED_TOOL_USE_ID = "toolu-exit-resume-target"; + const SEND = "toolu-exit-resume-sendmessage"; + const SEND_INPUT = { to: RESUMED_TASK_ID, message: "Check the last commit again." }; + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); + const now = yield* DateTime.now; + const sendItems = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === SEND + ? [ + `${event.turnItem.type}:${event.turnItem.status}:${JSON.stringify("input" in event.turnItem ? event.turnItem.input : null)}`, + ] + : [], ); - assert.equal(latest?.type, "subagent.updated"); - if (latest?.type !== "subagent.updated") return; - assert.equal(latest.subagent.status, resume ? "running" : "completed"); - assert.equal(latest.subagent.result, resume ? null : "Finished audit."); - assert.equal(latest.subagent.completedAt === null, resume); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - const makeStopFixture = (options?: Parameters[0]) => - Effect.gen(function* () { - const requests = yield* Queue.unbounded(); - const harness = yield* makeWakeHarnessWithOptions({ - ...options, - stopTask: (id) => - Queue.offer(requests, undefined).pipe( - Effect.andThen(options?.stopTask?.(id) ?? Effect.void), - ), - }); - let sequence = 4500; - const uuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; - const startTurn = (continuation = false) => - harness.runtime.startTurn( + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now: DateTime.makeUnsafe(0), - attemptId: RunAttemptId.make(`attempt-stop-${continuation ? 2 : 1}`), - providerTurnOrdinal: continuation ? 2 : 1, - text: "Run an audit.", + now, + attemptId: RunAttemptId.make("attempt-claude-exit-resume-1"), + text: "Run two auditors in the background.", attachments: [], - ...(continuation - ? { messageCreatedBy: "agent" as const, messageCreationSource: "provider" as const } - : {}), }), ); - const start = (toolUseId = "toolu-stop-agent") => - harness.offerAndWait( + for (const frame of [ makeSubagentTaskStartedFrame({ - taskId: "stop-agent", - toolUseId, - uuid: uuid(), + taskId: SENDER_TASK_ID, + toolUseId: SENDER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001101", }), - ); - const notify = ( - status: "completed" | "failed" | "stopped", - summary = "Native outcome.", - toolUseId = "toolu-stop-agent", - ) => - harness.offerAndWait( + makeSubagentTaskStartedFrame({ + taskId: RESUMED_TASK_ID, + toolUseId: RESUMED_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001102", + }), + makeSubagentNotificationFrame({ + taskId: RESUMED_TASK_ID, + toolUseId: RESUMED_TOOL_USE_ID, + summary: "First answer.", + uuid: "00000000-0000-4000-8000-000000001103", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001104", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + yield* Queue.offer( + harness.sdkMessages, claudeSdkFrame({ - ...makeSubagentNotificationFrame({ - taskId: "stop-agent", - toolUseId, - summary, - uuid: uuid(), - }), - status, + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_exit_resume_sendmessage", + type: "message", + role: "assistant", + content: [{ type: "tool_use", id: SEND, name: "SendMessage", input: SEND_INPUT }], + }, + parent_tool_use_id: SENDER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001105", + session_id: WAKE_NATIVE_SESSION, }), ); - const stop = (requestedAt?: DateTime.Utc) => - harness.runtime.stopSubagent!({ - providerThread: harness.providerThread, - nativeTaskId: "stop-agent", - ...(requestedAt === undefined ? {} : { requestedAt }), - }); - const finishParent = () => - harness - .offerAndWait(makeResultFrame({ uuid: uuid(), result: "Launched." })) - .pipe(Effect.andThen(Queue.take(harness.terminalReceipts))); - yield* startTurn(); - yield* start(); - yield* Queue.take(harness.subagentReceipts); - return { - ...harness, - start, - notify, - stop, - finishParent, - replay: () => startTurn(true), - uuid, - requests, - }; - }); + yield* harness.until(() => sendItems().length >= 1); - it.effect("retains native confirmation after the synchronous Agent tool result", () => - Effect.scoped( - Effect.gen(function* () { - const fixture = yield* makeStopFixture({ - stopTask: () => Effect.die("Task already completed"), - }); - yield* fixture.notify("completed"); - const completed = yield* Queue.take(fixture.subagentReceipts); - yield* fixture.offerAndWait( + for (const frame of [ + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: RESUMED_TASK_ID, + tool_use_id: SEND, + description: "Audit recent commits", + is_backgrounded: true, + task_type: "local_agent", + prompt: SEND_INPUT.message, + uuid: "00000000-0000-4000-8000-000000001106", + session_id: WAKE_NATIVE_SESSION, + }), claudeSdkFrame({ type: "user", message: { role: "user", - content: [ - { type: "tool_result", tool_use_id: "toolu-stop-agent", content: "Tool result." }, - ], + content: [{ type: "tool_result", tool_use_id: SEND, content: "Message sent." }], }, - parent_tool_use_id: null, - uuid: fixture.uuid(), + parent_tool_use_id: SENDER_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000001107", session_id: WAKE_NATIVE_SESSION, }), + makeSubagentNotificationFrame({ + taskId: RESUMED_TASK_ID, + toolUseId: SEND, + summary: "Second answer.", + uuid: "00000000-0000-4000-8000-000000001108", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitContinuation(1); + const beforeExit = sendItems(); + + yield* Queue.shutdown(harness.sdkMessages); + yield* yieldTicks(50); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-exit-resume-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), ); - assert.equal((yield* Queue.take(fixture.subagentReceipts)).subagent.result, "Tool result."); - assert.deepEqual(yield* fixture.stop(), { - status: "completed", - completedAt: completed.subagent.completedAt!, - result: "Native outcome.", - }); + assert.equal(harness.processQueues.length, 2); + yield* Queue.offer( + harness.processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001109", + result: "The audit finished.", + }), + ); + yield* harness.awaitTerminal(2); + + const input = JSON.stringify(SEND_INPUT); + assert.deepEqual(beforeExit, [`dynamic_tool:running:${input}`]); + assert.deepEqual(sendItems(), [ + `dynamic_tool:running:${input}`, + `dynamic_tool:completed:${input}`, + ]); }).pipe( Effect.provide( Layer.mergeAll( @@ -17964,320 +17521,165 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), - ); - - it.effect.each([ - [false, "stopped"], - [true, "stopped"], - [false, "completed"], - ] as const)( - "stops one native subagent while its sibling keeps running, owner settled %s, outcome %s", - ([ownerSettled, outcome]) => - Effect.scoped( - Effect.gen(function* () { - const stopped: string[] = []; - const stopRequested = yield* Deferred.make(); - let closes = 0; - const harness = yield* makeWakeHarnessWithOptions({ - stopTask: (taskId) => - Effect.sync(() => { - stopped.push(taskId); - }).pipe(Effect.andThen(Deferred.succeed(stopRequested, undefined))), - interrupt: Effect.die("A child stop must not interrupt its owner"), - close: () => - Effect.sync(() => { - closes++; - }), - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-native-child-stop"), - text: "Start two agents.", - attachments: [], - }), - ); - for (const [taskId, toolUseId, uuid] of [ - ["agent-stop", "toolu-stop", "00000000-0000-4000-8000-000000000801"], - ["agent-keep", "toolu-keep", "00000000-0000-4000-8000-000000000802"], - ]) { - yield* harness.offerAndWait( - makeSubagentTaskStartedFrame({ taskId: taskId!, toolUseId: toolUseId!, uuid: uuid! }), - ); - yield* Queue.take(harness.subagentReceipts); - } - if (ownerSettled) { - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000803", - result: "Agents are working.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - } - const stop = harness.runtime.stopSubagent; - assert.isDefined(stop); - const stopping = yield* stop!({ - providerThread: harness.providerThread, - nativeTaskId: "agent-stop", - }).pipe(Effect.forkScoped); - yield* Deferred.await(stopRequested); - assert.deepEqual(stopped, ["agent-stop"]); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...makeSubagentNotificationFrame({ - taskId: "agent-stop", - toolUseId: "toolu-stop", - summary: "Stopped by user", - uuid: "00000000-0000-4000-8000-000000000804", - }), - status: outcome, - }), - ); - if (ownerSettled) { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-native-child-stop-wake"), - text: "Background task stopped.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - } - yield* Fiber.join(stopping); - const stoppedEvent = yield* Queue.take(harness.subagentReceipts); - assert.equal( - stoppedEvent.subagent.status, - outcome === "stopped" ? "cancelled" : "completed", - ); - const tasks = harness.events.filter((event) => event.type === "subagent.updated"); - assert.equal( - tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-stop") - ?.subagent.status, - outcome === "stopped" ? "cancelled" : "completed", - ); - assert.equal( - tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-keep") - ?.subagent.status, - "running", - ); - assert.lengthOf(harness.terminalEvents(), ownerSettled ? 1 : 0); - yield* stop!({ providerThread: harness.providerThread, nativeTaskId: "agent-stop" }); - assert.deepEqual(stopped, ["agent-stop"]); - assert.equal(closes, 0); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), ); it.effect.each([ - "requested", - "observed-before", - "observed-after", - "synthetic-after", - "inherit", - "unknown", + ["", "none"], + [" behind another subagent's start without one", "before"], + [" when another subagent's start without one arrives between its frames", "between"], ] as const)( - "records the subagent model from %s without inheriting the parent override", - (source) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const toolUseId = "toolu-subagent-model"; - const parentModel = "claude-opus-4-6"; - // Claude stamps its error frames as "", regardless of the subagent model. - const observedModel = - source === "synthetic-after" ? "" : "claude-haiku-4-5-20251001"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-subagent-model"), - text: "Spawn a Haiku subagent.", - attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, - }), - ); - const observed = claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: toolUseId, - message: { - model: observedModel, - id: "msg_subagent_model_observed", - type: "message", - role: "assistant", - content: [{ type: "text", text: "Solving." }], - }, - uuid: "00000000-0000-4000-8000-000000000206", - session_id: WAKE_NATIVE_SESSION, - }); - if (source === "observed-before") yield* Queue.offer(harness.sdkMessages, observed); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: null, - message: { - model: parentModel, - id: "msg_subagent_model_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: toolUseId, - name: "Agent", - input: { - description: "Haiku puzzle", - subagent_type: "general-purpose", - ...(source === "unknown" - ? {} - : { model: source === "inherit" ? "inherit" : "haiku" }), - prompt: "Solve the puzzle.", - }, - }, - ], - }, - uuid: "00000000-0000-4000-8000-000000000209", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: "task-subagent-model", - tool_use_id: toolUseId, - description: "Haiku puzzle", - task_type: "local_agent", - uuid: "00000000-0000-4000-8000-000000000207", - session_id: WAKE_NATIVE_SESSION, - }), - ); - if (source === "observed-after" || source === "synthetic-after") { - yield* Queue.offer(harness.sdkMessages, observed); - } - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000208", - result: "Spawned the subagent.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - const subagents = harness.events.filter((event) => event.type === "subagent.updated"); - const observedSlug = "claude-haiku-4-5"; - const initialModel = - source === "observed-before" - ? observedSlug - : source === "inherit" - ? parentModel - : source === "unknown" - ? null - : "claude-haiku-5-5"; - assert.equal(subagents[0]?.subagent.model, initialModel); - assert.equal( - subagents.at(-1)?.subagent.model, - source.startsWith("observed") ? observedSlug : initialModel, - ); - const child = harness.events.find((event) => event.type === "app_thread.created"); - assert.equal(child?.appThread.modelSelection?.model, initialModel ?? parentModel); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("records a forked skill's model from its transcript instead of the parent's", () => - Effect.scoped( + "keeps a subagent's frames in order when a late progress names its tool use while the root is idle%s", + ([, otherStart]) => Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - subagentModel: "claude-haiku-4-5-20251001", - }); + const TASK_ID = "task-late-owner-idle"; + const TOOL_USE_ID = "toolu-late-owner-idle"; + const BASH = "toolu-late-owner-idle-bash"; + const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const parentModel = "claude-opus-4-6"; + const bashStatuses = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH + ? [`${event.turnItem.type}:${event.turnItem.status}`] + : [], + ); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-forked-skill-model"), - text: "/fork-probe go", + attemptId: RunAttemptId.make("attempt-claude-late-owner-idle-1"), + text: "Audit in the background.", attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, }), ); - // A `context: fork` skill has no Agent call and streams none of its own replies: - // task_started carries no tool_use_id, and only its prompt echo names the fork. for (const frame of [ claudeSdkFrame({ type: "system", subtype: "task_started", - task_id: "task-forked-skill", - description: "/fork-probe", - prompt: "go", + task_id: TASK_ID, + description: "Audit recent commits", subagent_type: "general-purpose", + is_backgrounded: true, task_type: "local_agent", - skip_transcript: true, - ambient: true, - uuid: "00000000-0000-4000-8000-000000000231", + prompt: "Audit the last five commits.", + uuid: "00000000-0000-4000-8000-000000000a01", session_id: WAKE_NATIVE_SESSION, }), - claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: "task-forked-skill", - status: "completed", - summary: "/fork-probe", - output_file: "", - uuid: "00000000-0000-4000-8000-000000000232", - session_id: WAKE_NATIVE_SESSION, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a02", + result: "Auditing in the background.", }), - claudeSdkFrame({ - type: "user", - parent_tool_use_id: "forked-command-fork-probe", - message: { role: "user", content: [{ type: "text", text: "go" }] }, - uuid: "00000000-0000-4000-8000-000000000233", - session_id: WAKE_NATIVE_SESSION, + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + const otherStartFrame = claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-late-owner-other", + description: "Check the changelog", + subagent_type: "general-purpose", + is_backgrounded: true, + task_type: "local_agent", + prompt: "Check the changelog.", + uuid: "00000000-0000-4000-8000-000000000a09", + session_id: WAKE_NATIVE_SESSION, + }); + const progressFrame = claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: TASK_ID, + tool_use_id: TOOL_USE_ID, + description: "Reading the last commits", + usage: { total_tokens: 1, tool_uses: 1, duration_ms: 1 }, + uuid: "00000000-0000-4000-8000-000000000a04", + session_id: WAKE_NATIVE_SESSION, + }); + const bashResultFrame = makeSubagentToolResultFrame({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a05", + toolUseId: BASH, + }); + for (const frame of [ + ...(otherStart === "before" ? [otherStartFrame] : []), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a03", + text: "First.", + bashToolUseId: BASH, + }), + ...(otherStart === "between" + ? [otherStartFrame, bashResultFrame, progressFrame] + : [progressFrame, bashResultFrame]), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a06", + text: "Second.", + }), + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + summary: "Second.", + uuid: "00000000-0000-4000-8000-000000000a07", }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* Queue.take(harness.terminalReceipts); + yield* harness.awaitContinuation(1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a08", + result: "The auditor finished.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-late-owner-idle-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(2); - const fork = harness.events - .filter((event) => event.type === "subagent.updated") - .at(-1)?.subagent; - assert.equal(fork?.status, "completed"); - assert.equal(fork?.model, "claude-haiku-4-5"); - assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); + const routing = subagentRouting(harness.events, [BASH]); + const childTexts = routing.assistantTexts(routing.childThreadId); + const statuses = bashStatuses(); + const trace = harness.events.flatMap((event) => + event.type === "message.updated" && + event.message.role === "assistant" && + event.message.threadId === routing.childThreadId + ? [`text:${event.message.text}#${event.message.id}`] + : event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH + ? [`bash:${event.turnItem.status}`] + : [], + ); + assert.deepEqual(childTexts, ["First.", "Second."], `trace: ${JSON.stringify(trace)}`); + assert.deepEqual( + [...(routing.toolThreadIds.get(BASH) ?? [])], + [routing.childThreadId], + `trace: ${JSON.stringify(trace)}`, + ); + assert.deepEqual( + statuses, + ["command_execution:running", "command_execution:completed"], + `trace: ${JSON.stringify(trace)}`, + ); + assert.isTrue( + harness.events.some( + (event) => + event.type === "subagent.updated" && + event.subagent.progress === "Reading the last commits", + ), + ); + assert.lengthOf(harness.continuationRequests, 1); }).pipe( Effect.provide( Layer.mergeAll( @@ -18288,297 +17690,414 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect.each([ - { - source: "custom model", - model: "claude-custom-tuned", - harness: { settings: ULTRACODE_CUSTOM_MODEL_CLAUDE_SETTINGS }, - }, - { - source: "downloaded catalog", - model: "claude-sonnet-5", - harness: { - modelCatalog: Effect.succeed({ - models: BUNDLED_CLAUDE_MODEL_CATALOG.models.map((entry) => - entry.model.slug === "claude-sonnet-5" - ? { - ...entry, - model: { - ...entry.model, - capabilities: { - optionDescriptors: [ - ...(entry.model.capabilities?.optionDescriptors ?? []), - { id: "ultracode", label: "Ultracode", type: "boolean" as const }, - ], - }, - }, - } - : entry, - ), + it.effect("holds subagent frames that precede task_started and shows its result once", () => + Effect.gen(function* () { + const TASK_ID = "task-early-subagent"; + const TOOL_USE_ID = "toolu-early-subagent"; + const FINAL_REPORT = "Early auditor done."; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-early-subagent"), + text: "Run an auditor.", + attachments: [], }), - }, - }, - ])( - "sends Ultracode with any effort on a model from the $source", - ({ harness: harnessOptions, model }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions(harnessOptions); - yield* harness.runtime.startTurn( + ); + const frames = [ + // Child frames can precede the task_started that registers their subagent. + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000321", + text: "Starting early.", + bashToolUseId: "toolu-early-bash", + }), + makeSubagentToolResultFrame({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000322", + toolUseId: "toolu-early-bash", + }), + makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000323", + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000324", + text: "Still working.", + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: TASK_ID, + description: "Checking the diffs", + uuid: "00000000-0000-4000-8000-000000000325", + session_id: WAKE_NATIVE_SESSION, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000326", + text: FINAL_REPORT, + }), + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + summary: FINAL_REPORT, + uuid: "00000000-0000-4000-8000-000000000327", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000328", + result: "The auditor finished.", + }), + ]; + for (const frame of frames) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + const routing = subagentRouting(harness.events, ["toolu-early-bash"]); + assert.isDefined(routing.childThreadId); + // Agents quote this id back to t3_thread_send/t3_thread_read. + const childThreadId = routing.childThreadId ?? ""; + assert.notInclude(childThreadId, "%"); + assert.isAtMost(childThreadId.length, 64); + assert.deepEqual( + [...(routing.toolThreadIds.get("toolu-early-bash") ?? [])], + [routing.childThreadId], + ); + assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ + "Starting early.", + "Still working.", + FINAL_REPORT, + ]); + assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each([false, true])( + "drops an idle start superseded by live completion, later resume %s", + (resume) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const startTurn = (ordinal: number, continuation = false) => + harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-custom-ultracode"), - text: "Plan the work.", + now: DateTime.makeUnsafe(0), + attemptId: RunAttemptId.make(`attempt-stale-start-${ordinal}`), + providerTurnOrdinal: ordinal, + text: "Continue work.", attachments: [], - modelSelection: { - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - model, - options: [ - { id: "effort", value: "high" }, - { id: "ultracode", value: true }, - ], - }, + ...(continuation + ? { + messageCreatedBy: "agent" as const, + messageCreationSource: "provider" as const, + } + : {}), }), ); - const options = harness.getOpenedOptions()!; - assert.equal(options.effort, "high"); - assert.equal((options.settings as { ultracode?: boolean }).ultracode, true); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const started = (taskId: string, suffix: string) => + makeSubagentTaskStartedFrame({ + taskId, + toolUseId: `toolu-${taskId}`, + uuid: `00000000-0000-4000-8000-${suffix}`, + }); + const finished = (taskId: string, suffix: string) => + makeSubagentNotificationFrame({ + taskId, + toolUseId: `toolu-${taskId}`, + summary: "Finished audit.", + uuid: `00000000-0000-4000-8000-${suffix}`, + }); + yield* startTurn(1); + yield* harness.offerAndWait(started("stale-agent", "000000004001")); + yield* harness.offerAndWait(started("wake-agent", "000000004002")); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000004003", + result: "Agents launched.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + yield* harness.offerAndWait(started("stale-agent", "000000004004")); + yield* startTurn(2); + yield* harness.offerAndWait(finished("stale-agent", "000000004005")); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000004006", + result: "User turn finished.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + if (resume) yield* harness.offerAndWait(started("stale-agent", "000000004007")); + yield* harness.offerAndWait(finished("wake-agent", "000000004008")); + yield* Queue.take(harness.continuationReceipts); + yield* startTurn(3, true); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000004009", + result: "Wake finished.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + const latest = harness.events.findLast( + (event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === "stale-agent", + ); + assert.equal(latest?.type, "subagent.updated"); + if (latest?.type !== "subagent.updated") return; + assert.equal(latest.subagent.status, resume ? "running" : "completed"); + assert.equal(latest.subagent.result, resume ? null : "Finished audit."); + assert.equal(latest.subagent.completedAt === null, resume); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("resolves a subagent's model and effort against the instance's custom models", () => - Effect.scoped( - Effect.gen(function* () { - const TUNED_TOOL_USE_ID = "toolu-effort-custom-tuned"; - const SHADOW_TOOL_USE_ID = "toolu-effort-custom-shadow"; - const harness = yield* makeWakeHarnessWithOptions({ - settings: CUSTOM_MODEL_CLAUDE_SETTINGS, - }); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( + const makeStopFixture = (options?: Parameters[0]) => + Effect.gen(function* () { + const requests = yield* Queue.unbounded(); + const harness = yield* makeWakeHarnessWithOptions({ + ...options, + stopTask: (id) => + Queue.offer(requests, undefined).pipe( + Effect.andThen(options?.stopTask?.(id) ?? Effect.void), + ), + }); + let sequence = 4500; + const uuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; + const startTurn = (continuation = false) => + harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-subagent-custom-effort"), - text: "Spawn subagents on custom models.", + now: DateTime.makeUnsafe(0), + attemptId: RunAttemptId.make(`attempt-stop-${continuation ? 2 : 1}`), + providerTurnOrdinal: continuation ? 2 : 1, + text: "Run an audit.", attachments: [], + ...(continuation + ? { messageCreatedBy: "agent" as const, messageCreationSource: "provider" as const } + : {}), }), ); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: null, - message: { - model: CLAUDE_TEST_MODEL_SELECTION.model, - id: "msg_custom_effort_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: TUNED_TOOL_USE_ID, - name: "Agent", - input: { - description: "Tuned", - subagent_type: "general-purpose", - model: "claude-custom-tuned", - effort: "brutal", - prompt: "Check one thing.", - }, - }, - { - type: "tool_use", - id: SHADOW_TOOL_USE_ID, - name: "Agent", - input: { - description: "Shadow", - subagent_type: "general-purpose", - model: "opus", - prompt: "Check another thing.", - }, - }, - ], - }, - uuid: "00000000-0000-4000-8000-000000000231", - session_id: WAKE_NATIVE_SESSION, + const start = (toolUseId = "toolu-stop-agent") => + harness.offerAndWait( + makeSubagentTaskStartedFrame({ + taskId: "stop-agent", + toolUseId, + uuid: uuid(), }), - ...[TUNED_TOOL_USE_ID, SHADOW_TOOL_USE_ID].map((id, index) => - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: `task-${id}`, - tool_use_id: id, - description: id, - task_type: "local_agent", - uuid: `00000000-0000-4000-8000-00000000023${index + 2}`, - session_id: WAKE_NATIVE_SESSION, + ); + const notify = ( + status: "completed" | "failed" | "stopped", + summary = "Native outcome.", + toolUseId = "toolu-stop-agent", + ) => + harness.offerAndWait( + claudeSdkFrame({ + ...makeSubagentNotificationFrame({ + taskId: "stop-agent", + toolUseId, + summary, + uuid: uuid(), }), - ), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000234", - result: "Spawned the subagents.", + status, }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.take(harness.terminalReceipts); - - const selections = Object.fromEntries( - harness.events.flatMap((event) => - event.type === "subagent.updated" - ? [[event.subagent.nativeTaskRef?.nativeId, event.subagent.modelSelection] as const] - : [], - ), ); - const instanceId = CLAUDE_TEST_MODEL_SELECTION.instanceId; - assert.deepEqual(selections, { - [`task-${TUNED_TOOL_USE_ID}`]: { - instanceId, - model: "claude-custom-tuned", - options: [{ id: "effort", value: "brutal" }], + const stop = (requestedAt?: DateTime.Utc) => + harness.runtime.stopSubagent!({ + providerThread: harness.providerThread, + nativeTaskId: "stop-agent", + ...(requestedAt === undefined ? {} : { requestedAt }), + }); + const finishParent = () => + harness + .offerAndWait(makeResultFrame({ uuid: uuid(), result: "Launched." })) + .pipe(Effect.andThen(Queue.take(harness.terminalReceipts))); + yield* startTurn(); + yield* start(); + yield* Queue.take(harness.subagentReceipts); + return { + ...harness, + start, + notify, + stop, + finishParent, + replay: () => startTurn(true), + uuid, + requests, + }; + }); + + it.effect("retains native confirmation after the synchronous Agent tool result", () => + Effect.gen(function* () { + const fixture = yield* makeStopFixture({ + stopTask: () => Effect.die("Task already completed"), + }); + yield* fixture.notify("completed"); + const completed = yield* Queue.take(fixture.subagentReceipts); + yield* fixture.offerAndWait( + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { type: "tool_result", tool_use_id: "toolu-stop-agent", content: "Tool result." }, + ], }, - [`task-${SHADOW_TOOL_USE_ID}`]: { instanceId, model: "opus" }, - }); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + parent_tool_use_id: null, + uuid: fixture.uuid(), + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.equal((yield* Queue.take(fixture.subagentReceipts)).subagent.result, "Tool result."); + assert.deepEqual(yield* fixture.stop(), { + status: "completed", + completedAt: completed.subagent.completedAt!, + result: "Native outcome.", + }); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("records only explicit effort for nested subagents", () => - Effect.scoped( + it.effect.each([ + [false, "stopped"], + [true, "stopped"], + [false, "completed"], + ] as const)( + "stops one native subagent while its sibling keeps running, owner settled %s, outcome %s", + ([ownerSettled, outcome]) => Effect.gen(function* () { - const OUTER_TOOL_USE_ID = "toolu-effort-outer"; - const UNSPECIFIED_TOOL_USE_ID = "toolu-effort-nested-unspecified"; - const OVERRIDING_TOOL_USE_ID = "toolu-effort-nested-overriding"; - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const parentSelection = { - instanceId: CLAUDE_TEST_MODEL_SELECTION.instanceId, - model: "claude-opus-4-6", - options: [{ id: "effort", value: "high" }], - } satisfies ModelSelection; + const stopped: string[] = []; + const stopRequested = yield* Deferred.make(); + let closes = 0; + const harness = yield* makeWakeHarnessWithOptions({ + stopTask: (taskId) => + Effect.sync(() => { + stopped.push(taskId); + }).pipe(Effect.andThen(Deferred.succeed(stopRequested, undefined))), + interrupt: Effect.die("A child stop must not interrupt its owner"), + close: () => + Effect.sync(() => { + closes++; + }), + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-subagent-nested-effort"), - text: "Spawn a subagent that spawns two more.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-native-child-stop"), + text: "Start two agents.", attachments: [], - modelSelection: parentSelection, }), ); - const agentCall = (id: string, effort?: string) => ({ - type: "tool_use" as const, - id, - name: "Agent", - input: { - description: id, - subagent_type: "general-purpose", - ...(effort === undefined ? {} : { effort }), - prompt: "Check one thing.", - }, - }); - const taskStarted = (id: string, uuid: string) => - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: `task-${id}`, - tool_use_id: id, - description: id, - task_type: "local_agent", - uuid, - session_id: WAKE_NATIVE_SESSION, - }); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: null, - message: { - model: parentSelection.model, - id: "msg_nested_effort_outer_launch", - type: "message", - role: "assistant", - content: [agentCall(OUTER_TOOL_USE_ID, "low")], - }, - uuid: "00000000-0000-4000-8000-000000000221", - session_id: WAKE_NATIVE_SESSION, - }), - taskStarted(OUTER_TOOL_USE_ID, "00000000-0000-4000-8000-000000000222"), + for (const [taskId, toolUseId, uuid] of [ + ["agent-stop", "toolu-stop", "00000000-0000-4000-8000-000000000801"], + ["agent-keep", "toolu-keep", "00000000-0000-4000-8000-000000000802"], + ]) { + yield* harness.offerAndWait( + makeSubagentTaskStartedFrame({ taskId: taskId!, toolUseId: toolUseId!, uuid: uuid! }), + ); + yield* Queue.take(harness.subagentReceipts); + } + if (ownerSettled) { + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000803", + result: "Agents are working.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + } + const stop = harness.runtime.stopSubagent; + assert.isDefined(stop); + const stopping = yield* stop!({ + providerThread: harness.providerThread, + nativeTaskId: "agent-stop", + }).pipe(Effect.forkScoped); + yield* Deferred.await(stopRequested); + assert.deepEqual(stopped, ["agent-stop"]); + yield* harness.offerAndWait( claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: OUTER_TOOL_USE_ID, - message: { - model: parentSelection.model, - id: "msg_nested_effort_inner_launch", - type: "message", - role: "assistant", - content: [ - agentCall(UNSPECIFIED_TOOL_USE_ID), - agentCall(OVERRIDING_TOOL_USE_ID, "max"), - ], - }, - uuid: "00000000-0000-4000-8000-000000000223", - session_id: WAKE_NATIVE_SESSION, - }), - taskStarted(UNSPECIFIED_TOOL_USE_ID, "00000000-0000-4000-8000-000000000224"), - taskStarted(OVERRIDING_TOOL_USE_ID, "00000000-0000-4000-8000-000000000225"), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000226", - result: "Spawned the subagents.", + ...makeSubagentNotificationFrame({ + taskId: "agent-stop", + toolUseId: "toolu-stop", + summary: "Stopped by user", + uuid: "00000000-0000-4000-8000-000000000804", + }), + status: outcome, }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); + ); + if (ownerSettled) { + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-native-child-stop-wake"), + text: "Background task stopped.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); } - yield* Queue.take(harness.terminalReceipts); - - const efforts = new Map( - harness.events.flatMap((event) => - event.type === "subagent.updated" - ? [ - [ - event.subagent.nativeTaskRef?.nativeId, - getModelSelectionStringOptionValue(event.subagent.modelSelection, "effort"), - ] as const, - ] - : [], - ), + yield* Fiber.join(stopping); + const stoppedEvent = yield* Queue.take(harness.subagentReceipts); + assert.equal( + stoppedEvent.subagent.status, + outcome === "stopped" ? "cancelled" : "completed", ); - assert.deepEqual(Object.fromEntries(efforts), { - [`task-${OUTER_TOOL_USE_ID}`]: "low", - [`task-${UNSPECIFIED_TOOL_USE_ID}`]: undefined, - [`task-${OVERRIDING_TOOL_USE_ID}`]: "max", - }); - const childEfforts = harness.events.flatMap((event) => - event.type === "app_thread.created" && event.appThread.id !== harness.threadId - ? [getModelSelectionStringOptionValue(event.appThread.modelSelection, "effort")] - : [], + const tasks = harness.events.filter((event) => event.type === "subagent.updated"); + assert.equal( + tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-stop") + ?.subagent.status, + outcome === "stopped" ? "cancelled" : "completed", + ); + assert.equal( + tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-keep") + ?.subagent.status, + "running", ); - assert.deepEqual(childEfforts, ["low", undefined, "max"]); + assert.lengthOf(harness.terminalEvents(), ownerSettled ? 1 : 0); + yield* stop!({ providerThread: harness.providerThread, nativeTaskId: "agent-stop" }); + assert.deepEqual(stopped, ["agent-stop"]); + assert.equal(closes, 0); }).pipe( Effect.provide( Layer.mergeAll( @@ -18589,169 +18108,122 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); it.effect.each([ - { - label: "extracts text from direct content-block subagent results", - content: [ - { type: "text", text: "First line." }, - { type: "text", text: "Second line." }, - ], - expected: "First line.\nSecond line.", - }, - { - label: "drops Claude Code's tools-used note from a subagent result", - content: [ - { - type: "text", - text: "Read\n\nadd (line 1)\nmean (line 6)", - }, - ], - expected: "add (line 1)\nmean (line 6)", - }, - ])("$label", ({ content, expected }) => - Effect.scoped( + "requested", + "observed-before", + "observed-after", + "synthetic-after", + "inherit", + "unknown", + ] as const)( + "records the subagent model from %s without inheriting the parent override", + (source) => Effect.gen(function* () { - const SUBAGENT_TASK_ID = "task-direct-content-blocks"; - const SUBAGENT_TOOL_USE_ID = "toolu-direct-content-blocks"; const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const subagentEvents = () => - harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "subagent.updated" } - > => event.type === "subagent.updated", - ); - + const toolUseId = "toolu-subagent-model"; + const parentModel = "claude-opus-4-6"; + // Claude stamps its error frames as "", regardless of the subagent model. + const observedModel = + source === "synthetic-after" ? "" : "claude-haiku-4-5-20251001"; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-direct-content-blocks"), - text: "Delegate this task.", + attemptId: RunAttemptId.make("attempt-subagent-model"), + text: "Spawn a Haiku subagent.", attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, }), ); + const observed = claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: toolUseId, + message: { + model: observedModel, + id: "msg_subagent_model_observed", + type: "message", + role: "assistant", + content: [{ type: "text", text: "Solving." }], + }, + uuid: "00000000-0000-4000-8000-000000000206", + session_id: WAKE_NATIVE_SESSION, + }); + if (source === "observed-before") yield* Queue.offer(harness.sdkMessages, observed); yield* Queue.offer( harness.sdkMessages, claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - description: "Delegated task", - subagent_type: "general-purpose", - task_type: "local_agent", - prompt: "Return the result.", - uuid: "00000000-0000-4000-8000-000000000206", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* harness.until(() => subagentEvents().length === 1); - - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "user", + type: "assistant", + parent_tool_use_id: null, message: { - role: "user", + model: parentModel, + id: "msg_subagent_model_launch", + type: "message", + role: "assistant", content: [ { - type: "tool_result", - tool_use_id: SUBAGENT_TOOL_USE_ID, - content, + type: "tool_use", + id: toolUseId, + name: "Agent", + input: { + description: "Haiku puzzle", + subagent_type: "general-purpose", + ...(source === "unknown" + ? {} + : { model: source === "inherit" ? "inherit" : "haiku" }), + prompt: "Solve the puzzle.", + }, }, ], }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000207", + uuid: "00000000-0000-4000-8000-000000000209", session_id: WAKE_NATIVE_SESSION, }), ); - yield* harness.until(() => subagentEvents().at(-1)?.subagent.status === "completed"); - - assert.equal(subagentEvents().at(-1)?.subagent.result, expected); - yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000208", - result: "Delegation completed.", - }), - ); - yield* harness.awaitTerminal(1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("keeps a foreground fork running past the placeholder result for its own launch", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-foreground-fork"), - text: "Fork this.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - makeSubagentTaskStartedFrame({ - taskId: "agent-fork", - toolUseId: "toolu-fork", - uuid: "00000000-0000-4000-8000-000000000901", - }), - ); - // Claude Code opens a foreground fork's own stream with a placeholder result for its launch. - yield* harness.offerAndWait( claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: "toolu-fork", - content: "Fork started — that fork is you.", - }, - ], - }, - parent_tool_use_id: "toolu-fork", - uuid: "00000000-0000-4000-8000-000000000902", + type: "system", + subtype: "task_started", + task_id: "task-subagent-model", + tool_use_id: toolUseId, + description: "Haiku puzzle", + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000207", session_id: WAKE_NATIVE_SESSION, }), ); - yield* harness.offerAndWait( - makeSubagentNotificationFrame({ - taskId: "agent-fork", - toolUseId: "toolu-fork", - summary: "FORK-DONE", - uuid: "00000000-0000-4000-8000-000000000903", + if (source === "observed-after" || source === "synthetic-after") { + yield* Queue.offer(harness.sdkMessages, observed); + } + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000208", + result: "Spawned the subagent.", }), ); - let settled = yield* Queue.take(harness.subagentReceipts); - while (settled.subagent.status === "running") { - settled = yield* Queue.take(harness.subagentReceipts); - } - assert.equal(settled.subagent.result, "FORK-DONE"); + yield* Queue.take(harness.terminalReceipts); + const subagents = harness.events.filter((event) => event.type === "subagent.updated"); + const observedSlug = "claude-haiku-4-5"; + const initialModel = + source === "observed-before" + ? observedSlug + : source === "inherit" + ? parentModel + : source === "unknown" + ? null + : "claude-haiku-5-5"; + assert.equal(subagents[0]?.subagent.model, initialModel); + assert.equal( + subagents.at(-1)?.subagent.model, + source.startsWith("observed") ? observedSlug : initialModel, + ); + const child = harness.events.find((event) => event.type === "app_thread.created"); + assert.equal(child?.appThread.modelSelection?.model, initialModel ?? parentModel); }).pipe( Effect.provide( Layer.mergeAll( @@ -18762,98 +18234,139 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), - ), ); - it.effect("releases the idle pin when a post-settle subagent stops without completing", () => - Effect.scoped( - Effect.gen(function* () { - const SUBAGENT_TASK_ID = "task-wake-subagent-stopped"; - const subagentTaskStarted = claudeSdkFrame({ + it.effect("records a forked skill's model from its transcript instead of the parent's", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + subagentModel: "claude-haiku-4-5-20251001", + }); + const now = yield* DateTime.now; + const parentModel = "claude-opus-4-6"; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-forked-skill-model"), + text: "/fork-probe go", + attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, + }), + ); + // A `context: fork` skill has no Agent call and streams none of its own replies: + // task_started carries no tool_use_id, and only its prompt echo names the fork. + for (const frame of [ + claudeSdkFrame({ type: "system", subtype: "task_started", - task_id: SUBAGENT_TASK_ID, - tool_use_id: "toolu-wake-subagent-stopped", - description: "Long-running research task", + task_id: "task-forked-skill", + description: "/fork-probe", + prompt: "go", subagent_type: "general-purpose", task_type: "local_agent", - prompt: "Investigate the flaky test.", - uuid: "00000000-0000-4000-8000-000000000301", + skip_transcript: true, + ambient: true, + uuid: "00000000-0000-4000-8000-000000000231", session_id: WAKE_NATIVE_SESSION, - }); - const subagentStoppedNotification = claudeSdkFrame({ + }), + claudeSdkFrame({ type: "system", subtype: "task_notification", - task_id: SUBAGENT_TASK_ID, - tool_use_id: "toolu-wake-subagent-stopped", - status: "stopped", - output_file: "/tmp/task-wake-subagent-stopped.output", - summary: "Agent was stopped before finishing.", - uuid: "00000000-0000-4000-8000-000000000302", + task_id: "task-forked-skill", + status: "completed", + summary: "/fork-probe", + output_file: "", + uuid: "00000000-0000-4000-8000-000000000232", session_id: WAKE_NATIVE_SESSION, - }); - - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const subagentEvents = () => - harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "subagent.updated" } - > => event.type === "subagent.updated", - ); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-7a"), - text: "Spawn a background subagent and stop.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); - yield* harness.until(() => subagentEvents().length >= 1); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000303", - result: "Spawned the subagent in the background.", - }), - ); - yield* harness.awaitTerminal(1); - assert.isTrue(yield* harness.hasPendingBackgroundWork); + }), + claudeSdkFrame({ + type: "user", + parent_tool_use_id: "forked-command-fork-probe", + message: { role: "user", content: [{ type: "text", text: "go" }] }, + uuid: "00000000-0000-4000-8000-000000000233", + session_id: WAKE_NATIVE_SESSION, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); - yield* Queue.offer(harness.sdkMessages, subagentStoppedNotification); - yield* harness.awaitContinuation(1); + const fork = harness.events + .filter((event) => event.type === "subagent.updated") + .at(-1)?.subagent; + assert.equal(fork?.status, "completed"); + assert.equal(fork?.model, "claude-haiku-4-5"); + assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000304", - result: "The subagent was stopped.", - }), - ); + it.effect.each([ + { + source: "custom model", + model: "claude-custom-tuned", + harness: { settings: ULTRACODE_CUSTOM_MODEL_CLAUDE_SETTINGS }, + }, + { + source: "downloaded catalog", + model: "claude-sonnet-5", + harness: { + modelCatalog: Effect.succeed({ + models: BUNDLED_CLAUDE_MODEL_CATALOG.models.map((entry) => + entry.model.slug === "claude-sonnet-5" + ? { + ...entry, + model: { + ...entry.model, + capabilities: { + optionDescriptors: [ + ...(entry.model.capabilities?.optionDescriptors ?? []), + { id: "ultracode", label: "Ultracode", type: "boolean" as const }, + ], + }, + }, + } + : entry, + ), + }), + }, + }, + ])( + "sends Ultracode with any effort on a model from the $source", + ({ harness: harnessOptions, model }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions(harnessOptions); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-7b"), - text: "Background task completed.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-custom-ultracode"), + text: "Plan the work.", attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", + modelSelection: { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model, + options: [ + { id: "effort", value: "high" }, + { id: "ultracode", value: true }, + ], + }, }), ); - yield* harness.awaitTerminal(2); - - assert.equal(subagentEvents().at(-1)?.subagent.status, "cancelled"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); + const options = harness.getOpenedOptions()!; + assert.equal(options.effort, "high"); + assert.equal((options.settings as { ultracode?: boolean }).ultracode, true); }).pipe( Effect.provide( Layer.mergeAll( @@ -18864,650 +18377,950 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("resolves a subagent's model and effort against the instance's custom models", () => + Effect.gen(function* () { + const TUNED_TOOL_USE_ID = "toolu-effort-custom-tuned"; + const SHADOW_TOOL_USE_ID = "toolu-effort-custom-shadow"; + const harness = yield* makeWakeHarnessWithOptions({ + settings: CUSTOM_MODEL_CLAUDE_SETTINGS, + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-subagent-custom-effort"), + text: "Spawn subagents on custom models.", + attachments: [], + }), + ); + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: CLAUDE_TEST_MODEL_SELECTION.model, + id: "msg_custom_effort_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: TUNED_TOOL_USE_ID, + name: "Agent", + input: { + description: "Tuned", + subagent_type: "general-purpose", + model: "claude-custom-tuned", + effort: "brutal", + prompt: "Check one thing.", + }, + }, + { + type: "tool_use", + id: SHADOW_TOOL_USE_ID, + name: "Agent", + input: { + description: "Shadow", + subagent_type: "general-purpose", + model: "opus", + prompt: "Check another thing.", + }, + }, + ], + }, + uuid: "00000000-0000-4000-8000-000000000231", + session_id: WAKE_NATIVE_SESSION, + }), + ...[TUNED_TOOL_USE_ID, SHADOW_TOOL_USE_ID].map((id, index) => + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: `task-${id}`, + tool_use_id: id, + description: id, + task_type: "local_agent", + uuid: `00000000-0000-4000-8000-00000000023${index + 2}`, + session_id: WAKE_NATIVE_SESSION, + }), + ), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000234", + result: "Spawned the subagents.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); + + const selections = Object.fromEntries( + harness.events.flatMap((event) => + event.type === "subagent.updated" + ? [[event.subagent.nativeTaskRef?.nativeId, event.subagent.modelSelection] as const] + : [], + ), + ); + const instanceId = CLAUDE_TEST_MODEL_SELECTION.instanceId; + assert.deepEqual(selections, { + [`task-${TUNED_TOOL_USE_ID}`]: { + instanceId, + model: "claude-custom-tuned", + options: [{ id: "effort", value: "brutal" }], + }, + [`task-${SHADOW_TOOL_USE_ID}`]: { instanceId, model: "opus" }, + }); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("records only explicit effort for nested subagents", () => + Effect.gen(function* () { + const OUTER_TOOL_USE_ID = "toolu-effort-outer"; + const UNSPECIFIED_TOOL_USE_ID = "toolu-effort-nested-unspecified"; + const OVERRIDING_TOOL_USE_ID = "toolu-effort-nested-overriding"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const parentSelection = { + instanceId: CLAUDE_TEST_MODEL_SELECTION.instanceId, + model: "claude-opus-4-6", + options: [{ id: "effort", value: "high" }], + } satisfies ModelSelection; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-subagent-nested-effort"), + text: "Spawn a subagent that spawns two more.", + attachments: [], + modelSelection: parentSelection, + }), + ); + const agentCall = (id: string, effort?: string) => ({ + type: "tool_use" as const, + id, + name: "Agent", + input: { + description: id, + subagent_type: "general-purpose", + ...(effort === undefined ? {} : { effort }), + prompt: "Check one thing.", + }, + }); + const taskStarted = (id: string, uuid: string) => + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: `task-${id}`, + tool_use_id: id, + description: id, + task_type: "local_agent", + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: parentSelection.model, + id: "msg_nested_effort_outer_launch", + type: "message", + role: "assistant", + content: [agentCall(OUTER_TOOL_USE_ID, "low")], + }, + uuid: "00000000-0000-4000-8000-000000000221", + session_id: WAKE_NATIVE_SESSION, + }), + taskStarted(OUTER_TOOL_USE_ID, "00000000-0000-4000-8000-000000000222"), + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: OUTER_TOOL_USE_ID, + message: { + model: parentSelection.model, + id: "msg_nested_effort_inner_launch", + type: "message", + role: "assistant", + content: [agentCall(UNSPECIFIED_TOOL_USE_ID), agentCall(OVERRIDING_TOOL_USE_ID, "max")], + }, + uuid: "00000000-0000-4000-8000-000000000223", + session_id: WAKE_NATIVE_SESSION, + }), + taskStarted(UNSPECIFIED_TOOL_USE_ID, "00000000-0000-4000-8000-000000000224"), + taskStarted(OVERRIDING_TOOL_USE_ID, "00000000-0000-4000-8000-000000000225"), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000226", + result: "Spawned the subagents.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); + + const efforts = new Map( + harness.events.flatMap((event) => + event.type === "subagent.updated" + ? [ + [ + event.subagent.nativeTaskRef?.nativeId, + getModelSelectionStringOptionValue(event.subagent.modelSelection, "effort"), + ] as const, + ] + : [], + ), + ); + assert.deepEqual(Object.fromEntries(efforts), { + [`task-${OUTER_TOOL_USE_ID}`]: "low", + [`task-${UNSPECIFIED_TOOL_USE_ID}`]: undefined, + [`task-${OVERRIDING_TOOL_USE_ID}`]: "max", + }); + const childEfforts = harness.events.flatMap((event) => + event.type === "app_thread.created" && event.appThread.id !== harness.threadId + ? [getModelSelectionStringOptionValue(event.appThread.modelSelection, "effort")] + : [], + ); + assert.deepEqual(childEfforts, ["low", undefined, "max"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect("re-opens a resumed subagent whose task_started races past settle", () => - Effect.scoped( - Effect.gen(function* () { - const SUBAGENT_TASK_ID = "task-resume-postsettle"; - const SUBAGENT_TOOL_USE_ID = "toolu-resume-postsettle"; - const RESUME_TOOL_USE_ID = "toolu-resume-postsettle-sendmessage"; - const FIRST_SUMMARY = "Answered early."; - const SECOND_SUMMARY = "RESUME_SETTLE_DONE"; - const subagentTaskStarted = claudeSdkFrame({ + it.effect.each([ + { + label: "extracts text from direct content-block subagent results", + content: [ + { type: "text", text: "First line." }, + { type: "text", text: "Second line." }, + ], + expected: "First line.\nSecond line.", + }, + { + label: "drops Claude Code's tools-used note from a subagent result", + content: [ + { + type: "text", + text: "Read\n\nadd (line 1)\nmean (line 6)", + }, + ], + expected: "add (line 1)\nmean (line 6)", + }, + ])("$label", ({ content, expected }) => + Effect.gen(function* () { + const SUBAGENT_TASK_ID = "task-direct-content-blocks"; + const SUBAGENT_TOOL_USE_ID = "toolu-direct-content-blocks"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const subagentEvents = () => + harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "subagent.updated" } + > => event.type === "subagent.updated", + ); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-direct-content-blocks"), + text: "Delegate this task.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ type: "system", subtype: "task_started", task_id: SUBAGENT_TASK_ID, tool_use_id: SUBAGENT_TOOL_USE_ID, - description: "Sleep then echo done token", + description: "Delegated task", subagent_type: "general-purpose", task_type: "local_agent", - prompt: "Run the shell command, then return exactly RESUME_SETTLE_DONE.", - uuid: "00000000-0000-4000-8000-000000000501", - session_id: WAKE_NATIVE_SESSION, - }); - const firstNotification = claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - status: "completed", - output_file: "/tmp/task-resume-postsettle.output", - summary: FIRST_SUMMARY, - uuid: "00000000-0000-4000-8000-000000000502", + prompt: "Return the result.", + uuid: "00000000-0000-4000-8000-000000000206", session_id: WAKE_NATIVE_SESSION, - }); - const resumeTaskStarted = claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: SUBAGENT_TASK_ID, - tool_use_id: RESUME_TOOL_USE_ID, - description: "Sleep then echo done token", - is_backgrounded: true, - task_type: "local_agent", - uuid: "00000000-0000-4000-8000-000000000505", + }), + ); + yield* harness.until(() => subagentEvents().length === 1); + + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: SUBAGENT_TOOL_USE_ID, + content, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000207", session_id: WAKE_NATIVE_SESSION, - }); - const secondNotification = claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: SUBAGENT_TASK_ID, - tool_use_id: RESUME_TOOL_USE_ID, - status: "completed", - output_file: "/tmp/task-resume-postsettle.output", - summary: SECOND_SUMMARY, - uuid: "00000000-0000-4000-8000-000000000506", + }), + ); + yield* harness.until(() => subagentEvents().at(-1)?.subagent.status === "completed"); + + assert.equal(subagentEvents().at(-1)?.subagent.result, expected); + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000208", + result: "Delegation completed.", + }), + ); + yield* harness.awaitTerminal(1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("keeps a foreground fork running past the placeholder result for its own launch", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-foreground-fork"), + text: "Fork this.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + makeSubagentTaskStartedFrame({ + taskId: "agent-fork", + toolUseId: "toolu-fork", + uuid: "00000000-0000-4000-8000-000000000901", + }), + ); + // Claude Code opens a foreground fork's own stream with a placeholder result for its launch. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu-fork", + content: "Fork started — that fork is you.", + }, + ], + }, + parent_tool_use_id: "toolu-fork", + uuid: "00000000-0000-4000-8000-000000000902", session_id: WAKE_NATIVE_SESSION, - }); + }), + ); + yield* harness.offerAndWait( + makeSubagentNotificationFrame({ + taskId: "agent-fork", + toolUseId: "toolu-fork", + summary: "FORK-DONE", + uuid: "00000000-0000-4000-8000-000000000903", + }), + ); + let settled = yield* Queue.take(harness.subagentReceipts); + while (settled.subagent.status === "running") { + settled = yield* Queue.take(harness.subagentReceipts); + } + assert.equal(settled.subagent.result, "FORK-DONE"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const subagentEvents = () => - harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "subagent.updated" } - > => event.type === "subagent.updated", - ); + it.effect("releases the idle pin when a post-settle subagent stops without completing", () => + Effect.gen(function* () { + const SUBAGENT_TASK_ID = "task-wake-subagent-stopped"; + const subagentTaskStarted = claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: "toolu-wake-subagent-stopped", + description: "Long-running research task", + subagent_type: "general-purpose", + task_type: "local_agent", + prompt: "Investigate the flaky test.", + uuid: "00000000-0000-4000-8000-000000000301", + session_id: WAKE_NATIVE_SESSION, + }); + const subagentStoppedNotification = claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: SUBAGENT_TASK_ID, + tool_use_id: "toolu-wake-subagent-stopped", + status: "stopped", + output_file: "/tmp/task-wake-subagent-stopped.output", + summary: "Agent was stopped before finishing.", + uuid: "00000000-0000-4000-8000-000000000302", + session_id: WAKE_NATIVE_SESSION, + }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-9a"), - text: "Spawn a background subagent and stop.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); - yield* harness.until(() => subagentEvents().length >= 1); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000503", - result: "Spawned the subagent in the background.", - }), + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const subagentEvents = () => + harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "subagent.updated" } + > => event.type === "subagent.updated", ); - yield* harness.awaitTerminal(1); - yield* Queue.offer(harness.sdkMessages, firstNotification); - yield* harness.awaitContinuation(1); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000504", - result: "The subagent answered early.", - }), - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-9b"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.awaitTerminal(2); - assert.equal(subagentEvents().at(-1)?.subagent.status, "completed"); - assert.equal(subagentEvents().at(-1)?.subagent.result, FIRST_SUMMARY); - assert.isFalse(yield* harness.hasPendingBackgroundWork); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-7a"), + text: "Spawn a background subagent and stop.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); + yield* harness.until(() => subagentEvents().length >= 1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000303", + result: "Spawned the subagent in the background.", + }), + ); + yield* harness.awaitTerminal(1); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + yield* Queue.offer(harness.sdkMessages, subagentStoppedNotification); + yield* harness.awaitContinuation(1); + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000304", + result: "The subagent was stopped.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-7b"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(2); + + assert.equal(subagentEvents().at(-1)?.subagent.status, "cancelled"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("re-opens a resumed subagent whose task_started races past settle", () => + Effect.gen(function* () { + const SUBAGENT_TASK_ID = "task-resume-postsettle"; + const SUBAGENT_TOOL_USE_ID = "toolu-resume-postsettle"; + const RESUME_TOOL_USE_ID = "toolu-resume-postsettle-sendmessage"; + const FIRST_SUMMARY = "Answered early."; + const SECOND_SUMMARY = "RESUME_SETTLE_DONE"; + const subagentTaskStarted = claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + description: "Sleep then echo done token", + subagent_type: "general-purpose", + task_type: "local_agent", + prompt: "Run the shell command, then return exactly RESUME_SETTLE_DONE.", + uuid: "00000000-0000-4000-8000-000000000501", + session_id: WAKE_NATIVE_SESSION, + }); + const firstNotification = claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + status: "completed", + output_file: "/tmp/task-resume-postsettle.output", + summary: FIRST_SUMMARY, + uuid: "00000000-0000-4000-8000-000000000502", + session_id: WAKE_NATIVE_SESSION, + }); + const resumeTaskStarted = claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: RESUME_TOOL_USE_ID, + description: "Sleep then echo done token", + is_backgrounded: true, + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000505", + session_id: WAKE_NATIVE_SESSION, + }); + const secondNotification = claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: SUBAGENT_TASK_ID, + tool_use_id: RESUME_TOOL_USE_ID, + status: "completed", + output_file: "/tmp/task-resume-postsettle.output", + summary: SECOND_SUMMARY, + uuid: "00000000-0000-4000-8000-000000000506", + session_id: WAKE_NATIVE_SESSION, + }); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_resume_postsettle_sendmessage", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: RESUME_TOOL_USE_ID, - name: "SendMessage", - input: { - to: SUBAGENT_TASK_ID, - summary: "Resume the subagent", - message: "Continue and return the token.", - }, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000508", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer(harness.sdkMessages, resumeTaskStarted); - const resumeAck = { - success: true, - message: `Resuming agent ${SUBAGENT_TASK_ID.slice(0, 7)}`, - resumedAgentId: SUBAGENT_TASK_ID, - pin: { id: SUBAGENT_TASK_ID, name: SUBAGENT_TASK_ID, ref: "42ab31" }, - }; - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - tool_use_id: RESUME_TOOL_USE_ID, - type: "tool_result", - content: [ - { - type: "text", - text: encodeJsonString(resumeAck), - }, - ], - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000509", - session_id: WAKE_NATIVE_SESSION, - tool_use_result: resumeAck, - }), + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const subagentEvents = () => + harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "subagent.updated" } + > => event.type === "subagent.updated", ); - for (const frame of [ - ...makeSubagentAssistantFrames({ - parentToolUseId: SUBAGENT_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000961", - text: "RESUMED_WORK", - bashToolUseId: "toolu-resume-postsettle-bash", - }), - makeSubagentToolResultFrame({ - parentToolUseId: SUBAGENT_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000962", - toolUseId: "toolu-resume-postsettle-bash", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.offer(harness.sdkMessages, secondNotification); - yield* harness.awaitContinuation(2); - assert.equal(harness.continuationRequests[1]?.detail, SECOND_SUMMARY); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000507", - result: "The subagent finished with RESUME_SETTLE_DONE.", - }), - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-9c"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* harness.awaitTerminal(3); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-9a"), + text: "Spawn a background subagent and stop.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); + yield* harness.until(() => subagentEvents().length >= 1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000503", + result: "Spawned the subagent in the background.", + }), + ); + yield* harness.awaitTerminal(1); - const statuses = subagentEvents().map((event) => event.subagent.status); - const firstCompleted = statuses.indexOf("completed"); - const reopenedIndex = statuses.lastIndexOf("running"); - assert.isAbove(reopenedIndex, firstCompleted); - assert.isNull(subagentEvents()[reopenedIndex]?.subagent.result); - assert.equal(subagentEvents()[reopenedIndex]?.subagent.runId, "run-attempt-claude-wake-9c"); - const nodeStatuses = harness.events - .filter( - ( - event, - ): event is Extract => - event.type === "node.updated" && - event.node.kind === "subagent" && - event.node.nativeItemRef?.nativeId === SUBAGENT_TASK_ID, - ) - .map((event) => event.node.status); - assert.isAbove(nodeStatuses.lastIndexOf("running"), nodeStatuses.indexOf("completed")); - const finalSubagent = subagentEvents().at(-1)?.subagent; - assert.equal(finalSubagent?.status, "completed"); - assert.equal(finalSubagent?.result, SECOND_SUMMARY); - assert.equal(finalSubagent?.runId, "run-attempt-claude-wake-9c"); - const reopenIndex = harness.events.findIndex( - (event) => - event.type === "subagent.updated" && - event.subagent.status === "running" && - event.subagent.runId === "run-attempt-claude-wake-9c", - ); - assert.isAtLeast(reopenIndex, 0); - const resumedWorkIndexes = harness.events.flatMap((event, index) => - event.type === "message.updated" && event.message.text === "RESUMED_WORK" ? [index] : [], - ); - assert.lengthOf(resumedWorkIndexes, 1); - assert.isAbove(resumedWorkIndexes[0] ?? -1, reopenIndex); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* Queue.offer(harness.sdkMessages, firstNotification); + yield* harness.awaitContinuation(1); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000504", + result: "The subagent answered early.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-9b"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(2); + assert.equal(subagentEvents().at(-1)?.subagent.status, "completed"); + assert.equal(subagentEvents().at(-1)?.subagent.result, FIRST_SUMMARY); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_resume_postsettle_sendmessage", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: RESUME_TOOL_USE_ID, + name: "SendMessage", + input: { + to: SUBAGENT_TASK_ID, + summary: "Resume the subagent", + message: "Continue and return the token.", + }, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000508", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer(harness.sdkMessages, resumeTaskStarted); + const resumeAck = { + success: true, + message: `Resuming agent ${SUBAGENT_TASK_ID.slice(0, 7)}`, + resumedAgentId: SUBAGENT_TASK_ID, + pin: { id: SUBAGENT_TASK_ID, name: SUBAGENT_TASK_ID, ref: "42ab31" }, + }; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + tool_use_id: RESUME_TOOL_USE_ID, + type: "tool_result", + content: [ + { + type: "text", + text: encodeJsonString(resumeAck), + }, + ], + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000509", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: resumeAck, + }), + ); + for (const frame of [ + ...makeSubagentAssistantFrames({ + parentToolUseId: SUBAGENT_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000961", + text: "RESUMED_WORK", + bashToolUseId: "toolu-resume-postsettle-bash", + }), + makeSubagentToolResultFrame({ + parentToolUseId: SUBAGENT_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000962", + toolUseId: "toolu-resume-postsettle-bash", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.offer(harness.sdkMessages, secondNotification); + yield* harness.awaitContinuation(2); + assert.equal(harness.continuationRequests[1]?.detail, SECOND_SUMMARY); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000507", + result: "The subagent finished with RESUME_SETTLE_DONE.", + }), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-9c"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + + const statuses = subagentEvents().map((event) => event.subagent.status); + const firstCompleted = statuses.indexOf("completed"); + const reopenedIndex = statuses.lastIndexOf("running"); + assert.isAbove(reopenedIndex, firstCompleted); + assert.isNull(subagentEvents()[reopenedIndex]?.subagent.result); + assert.equal(subagentEvents()[reopenedIndex]?.subagent.runId, "run-attempt-claude-wake-9c"); + const nodeStatuses = harness.events + .filter( + ( + event, + ): event is Extract => + event.type === "node.updated" && + event.node.kind === "subagent" && + event.node.nativeItemRef?.nativeId === SUBAGENT_TASK_ID, + ) + .map((event) => event.node.status); + assert.isAbove(nodeStatuses.lastIndexOf("running"), nodeStatuses.indexOf("completed")); + const finalSubagent = subagentEvents().at(-1)?.subagent; + assert.equal(finalSubagent?.status, "completed"); + assert.equal(finalSubagent?.result, SECOND_SUMMARY); + assert.equal(finalSubagent?.runId, "run-attempt-claude-wake-9c"); + const reopenIndex = harness.events.findIndex( + (event) => + event.type === "subagent.updated" && + event.subagent.status === "running" && + event.subagent.runId === "run-attempt-claude-wake-9c", + ); + assert.isAtLeast(reopenIndex, 0); + const resumedWorkIndexes = harness.events.flatMap((event, index) => + event.type === "message.updated" && event.message.text === "RESUMED_WORK" ? [index] : [], + ); + assert.lengthOf(resumedWorkIndexes, 1); + assert.isAbove(resumedWorkIndexes[0] ?? -1, reopenIndex); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect("resets Waiting roster and wake eligibility when the CLI process is replaced", () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-process-reset-", - }); - const processQueues: Array> = []; - const events: Array = []; - const continuationRequests: Array = - []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }).pipe(Effect.andThen(changes.notify)), - }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-process-reset"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-process-reset"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => + Effect.gen(function* () { + const changes = yield* makeChangeSignal; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-process-reset-", + }); + const processQueues: Array> = []; + const events: Array = []; + const continuationRequests: Array = + []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + continuationRequests: { + offer: (request) => Effect.sync(() => { - events.push(event); + continuationRequests.push(request); }).pipe(Effect.andThen(changes.notify)), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const now = yield* DateTime.now; - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-process-reset-a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - assert.equal(processQueues.length, 1); - const firstProcess = processQueues[0]!; - yield* Queue.offer(firstProcess, wakeTaskStarted); - yield* Queue.offer( - firstProcess, - claudeSdkFrame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [], - uuid: "00000000-0000-4000-8000-000000000603", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer(firstProcess, turnOneResult); - yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); - assert.isFalse(yield* hasPendingBackgroundWork); + }, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-process-reset"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-process-reset"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const now = yield* DateTime.now; - const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; - const activeProviderThread = { - ...providerThread, - status: "active" as const, - } satisfies OrchestrationV2ProviderThread; - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: activeProviderThread, - now, - attemptId: RunAttemptId.make("attempt-claude-process-reset-b"), - text: "Continue after process restart.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ); - assert.equal(processQueues.length, 2); + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-process-reset-a"), + text: "Run the build in the background.", + attachments: [], + }), + ); + assert.equal(processQueues.length, 1); + const firstProcess = processQueues[0]!; + yield* Queue.offer(firstProcess, wakeTaskStarted); + yield* Queue.offer( + firstProcess, + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000603", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer(firstProcess, turnOneResult); + yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); + assert.isFalse(yield* hasPendingBackgroundWork); + + const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; + const activeProviderThread = { + ...providerThread, + status: "active" as const, + } satisfies OrchestrationV2ProviderThread; + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: activeProviderThread, + now, + attemptId: RunAttemptId.make("attempt-claude-process-reset-b"), + text: "Continue after process restart.", + attachments: [], + providerTurnOrdinal: 2, + modelSelection: alternateModel, + }), + ); + assert.equal(processQueues.length, 2); - yield* changes.until(() => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.status === "active" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0 && - event.providerThread.updatedAt !== undefined, - ), - ); - assert.isFalse(yield* hasPendingBackgroundWork); - const emptyActiveRosterEvents = providerThreadRosterEvents(events).filter( + yield* changes.until(() => + providerThreadRosterEvents(events).some( (event) => event.providerThread.status === "active" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, - ); - assert.isAtLeast(emptyActiveRosterEvents.length, 1); - assert.deepEqual( - emptyActiveRosterEvents.at(-1)?.providerThread.pendingBackgroundTasks ?? [], - [], - ); - assert.equal(emptyActiveRosterEvents.at(-1)?.providerThread.status, "active"); - - const secondProcess = processQueues[1]!; - yield* Queue.offer(secondProcess, wakeNotification); - yield* yieldTicks(50); - assert.lengthOf(continuationRequests, 0); - - yield* Queue.offer( - secondProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000602", - result: "Process restart turn finished.", - }), - ); - yield* changes.until( - () => events.filter((event) => event.type === "turn.terminal").length === 2, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0 && + event.providerThread.updatedAt !== undefined, ), - ), - ), - ); - - it.effect( - "preserves buffered local_bash notification classification across model/policy query replacement", - () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-buffer-replace-", - }); - const processQueues: Array> = []; - const events: Array = []; - const continuationRequests: Array = - []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }).pipe(Effect.andThen(changes.notify)), - }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-buffer-replace"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-buffer-replace"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe(Effect.andThen(changes.notify)), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "Claude adapter runtime must expose hasPendingBackgroundWork.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const now = yield* DateTime.now; + ); + assert.isFalse(yield* hasPendingBackgroundWork); + const emptyActiveRosterEvents = providerThreadRosterEvents(events).filter( + (event) => + event.providerThread.status === "active" && + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + assert.isAtLeast(emptyActiveRosterEvents.length, 1); + assert.deepEqual( + emptyActiveRosterEvents.at(-1)?.providerThread.pendingBackgroundTasks ?? [], + [], + ); + assert.equal(emptyActiveRosterEvents.at(-1)?.providerThread.status, "active"); - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-buffer-replace-a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - assert.equal(processQueues.length, 1); - const firstProcess = processQueues[0]!; - yield* Queue.offer(firstProcess, wakeTaskStarted); - yield* Queue.offer(firstProcess, turnOneResult); - yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); - assert.isTrue(yield* hasPendingBackgroundWork); - - yield* Queue.offer(firstProcess, wakeNotification); - yield* yieldTicks(50); - assert.lengthOf(continuationRequests, 0); - - const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-claude-buffer-replace-user"), - text: "Switch model while background work completes.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ); - assert.equal(processQueues.length, 2); - const secondProcess = processQueues[1]!; - yield* Queue.offer( - secondProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000701", - result: "User turn finished after model switch.", - }), - ); - yield* changes.until( - () => events.filter((event) => event.type === "turn.terminal").length === 2, - ); - assert.isFalse(yield* hasPendingBackgroundWork); - assert.lengthOf(continuationRequests, 0); + const secondProcess = processQueues[1]!; + yield* Queue.offer(secondProcess, wakeNotification); + yield* yieldTicks(50); + assert.lengthOf(continuationRequests, 0); - yield* Queue.offer(secondProcess, wakeResult); - yield* changes.until(() => continuationRequests.length === 1); - assert.equal(continuationRequests[0]?.detail, WAKE_SUMMARY); - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-claude-buffer-replace-cont"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 3, - modelSelection: alternateModel, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* changes.until( - () => events.filter((event) => event.type === "turn.terminal").length === 3, - ); - assert.isTrue( - events.some( - (event) => - event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, - ), - ); - assert.isFalse( - events.some( - (event) => - event.type === "subagent.updated" || - (event.type === "node.updated" && event.node.kind === "subagent"), - ), - ); - assert.isFalse( - events.some( - (event) => - event.type !== "provider_thread.updated" && - JSON.stringify(event).includes(WAKE_TASK_ID), - ), - ); - assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + yield* Queue.offer( + secondProcess, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000602", + result: "Process restart turn finished.", + }), + ); + yield* changes.until( + () => events.filter((event) => event.type === "turn.terminal").length === 2, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect("refuses a thinking change that would kill a running background subagent", () => - Effect.scoped( + it.effect( + "preserves buffered local_bash notification classification across model/policy query replacement", + () => Effect.gen(function* () { const changes = yield* makeChangeSignal; - const SUBAGENT_TASK_ID = "task-model-change-running-subagent"; - const SUBAGENT_TOOL_USE_ID = "toolu-model-change-running-subagent"; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-model-change-running-subagent-", + prefix: "t3-claude-v2-buffer-replace-", }); const processQueues: Array> = []; const events: Array = []; + const continuationRequests: Array = + []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, @@ -19517,7 +19330,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { path: yield* Path.Path, random: yield* SecureRandom.SecureRandom, idAllocator, - continuationRequests: { offer: () => Effect.void }, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }).pipe(Effect.andThen(changes.notify)), + }, queryRunner: { allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), open: () => @@ -19546,12 +19364,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { assertComplete: Effect.void, }, }); - const threadId = ThreadId.make("thread-claude-model-change-running-subagent"); + const threadId = ThreadId.make("thread-claude-buffer-replace"); const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-claude-model-change-running-subagent", - ), + providerSessionId: ProviderSessionId.make("provider-session-claude-buffer-replace"), modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, }); @@ -19568,7 +19384,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), Effect.forkScoped, ); - const terminals = () => events.filter((event) => event.type === "turn.terminal"); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; const now = yield* DateTime.now; yield* runtime.startTurn( @@ -19576,107 +19395,90 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId, providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-model-change-running-subagent-a"), - text: "Spawn a background subagent and stop.", + attemptId: RunAttemptId.make("attempt-claude-buffer-replace-a"), + text: "Run the build in the background.", attachments: [], }), ); + assert.equal(processQueues.length, 1); const firstProcess = processQueues[0]!; - yield* Queue.offer( - firstProcess, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - description: "Background research", - subagent_type: "general-purpose", - task_type: "local_agent", - prompt: "Research, then report.", - uuid: "00000000-0000-4000-8000-000000000901", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - firstProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000902", - result: "Spawned the subagent in the background.", - }), - ); - yield* changes.until(() => terminals().length === 1); - const settledTurn = terminals()[0]!; + yield* Queue.offer(firstProcess, wakeTaskStarted); + yield* Queue.offer(firstProcess, turnOneResult); + yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); + assert.isTrue(yield* hasPendingBackgroundWork); - assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread)); - assert.isTrue( - yield* runtime.hasPendingBackgroundWorkForThread!(providerThread, { - includeSubagents: true, - }), - ); - assert.isFalse( - yield* runtime.hasPendingBackgroundWorkForThread!( - { - ...providerThread, - nativeThreadRef: { - ...providerThread.nativeThreadRef!, - nativeId: "sibling-native-session", - }, - }, - { includeSubagents: true }, - ), - ); + yield* Queue.offer(firstProcess, wakeNotification); + yield* yieldTicks(50); + assert.lengthOf(continuationRequests, 0); const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; - const switchTurn = (attempt: string) => - runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make(attempt), - text: "Switch model while the subagent runs.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ); - const refused = yield* switchTurn("attempt-claude-model-change-running-subagent-b").pipe( - Effect.flip, - ); - assert.equal( - makeProviderFailure({ cause: refused, class: "provider_error" }).message, - new ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError().message, + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make("attempt-claude-buffer-replace-user"), + text: "Switch model while background work completes.", + attachments: [], + providerTurnOrdinal: 2, + modelSelection: alternateModel, + }), ); - assert.lengthOf(processQueues, 1); - - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: settledTurn.providerTurnId, - requestRuntimeRestart: true, - }); - yield* switchTurn("attempt-claude-model-change-running-subagent-c"); - assert.lengthOf(processQueues, 2); - + assert.equal(processQueues.length, 2); + const secondProcess = processQueues[1]!; yield* Queue.offer( - processQueues[1]!, + secondProcess, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000903", - result: "Switched model.", + uuid: "00000000-0000-4000-8000-000000000701", + result: "User turn finished after model switch.", }), ); - yield* changes.until(() => terminals().length === 2); + yield* changes.until( + () => events.filter((event) => event.type === "turn.terminal").length === 2, + ); + assert.isFalse(yield* hasPendingBackgroundWork); + assert.lengthOf(continuationRequests, 0); + + yield* Queue.offer(secondProcess, wakeResult); + yield* changes.until(() => continuationRequests.length === 1); + assert.equal(continuationRequests[0]?.detail, WAKE_SUMMARY); yield* runtime.startTurn( makeClaudeTestTurnInput({ threadId, providerThread: { ...providerThread, status: "active" }, now, - attemptId: RunAttemptId.make("attempt-claude-model-change-running-subagent-d"), - text: "Switch back.", + attemptId: RunAttemptId.make("attempt-claude-buffer-replace-cont"), + text: "Background task completed.", attachments: [], providerTurnOrdinal: 3, + modelSelection: alternateModel, + messageCreatedBy: "agent", + messageCreationSource: "provider", }), ); - assert.lengthOf(processQueues, 3); + yield* changes.until( + () => events.filter((event) => event.type === "turn.terminal").length === 3, + ); + assert.isTrue( + events.some( + (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, + ), + ); + assert.isFalse( + events.some( + (event) => + event.type === "subagent.updated" || + (event.type === "node.updated" && event.node.kind === "subagent"), + ), + ); + assert.isFalse( + events.some( + (event) => + event.type !== "provider_thread.updated" && + JSON.stringify(event).includes(WAKE_TASK_ID), + ), + ); + assert.isFalse(yield* hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -19687,303 +19489,352 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("refuses a thinking change that would kill a running background subagent", () => + Effect.gen(function* () { + const changes = yield* makeChangeSignal; + const SUBAGENT_TASK_ID = "task-model-change-running-subagent"; + const SUBAGENT_TOOL_USE_ID = "toolu-model-change-running-subagent"; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-model-change-running-subagent-", + }); + const processQueues: Array> = []; + const events: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + continuationRequests: { offer: () => Effect.void }, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-model-change-running-subagent"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-claude-model-change-running-subagent", + ), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + const terminals = () => events.filter((event) => event.type === "turn.terminal"); + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-model-change-running-subagent-a"), + text: "Spawn a background subagent and stop.", + attachments: [], + }), + ); + const firstProcess = processQueues[0]!; + yield* Queue.offer( + firstProcess, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + description: "Background research", + subagent_type: "general-purpose", + task_type: "local_agent", + prompt: "Research, then report.", + uuid: "00000000-0000-4000-8000-000000000901", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + firstProcess, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000902", + result: "Spawned the subagent in the background.", + }), + ); + yield* changes.until(() => terminals().length === 1); + const settledTurn = terminals()[0]!; + + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread)); + assert.isTrue( + yield* runtime.hasPendingBackgroundWorkForThread!(providerThread, { + includeSubagents: true, + }), + ); + assert.isFalse( + yield* runtime.hasPendingBackgroundWorkForThread!( + { + ...providerThread, + nativeThreadRef: { + ...providerThread.nativeThreadRef!, + nativeId: "sibling-native-session", + }, + }, + { includeSubagents: true }, + ), + ); + + const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; + const switchTurn = (attempt: string) => + runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make(attempt), + text: "Switch model while the subagent runs.", + attachments: [], + providerTurnOrdinal: 2, + modelSelection: alternateModel, + }), + ); + const refused = yield* switchTurn("attempt-claude-model-change-running-subagent-b").pipe( + Effect.flip, + ); + assert.equal( + makeProviderFailure({ cause: refused, class: "provider_error" }).message, + new ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError().message, + ); + assert.lengthOf(processQueues, 1); + + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: settledTurn.providerTurnId, + requestRuntimeRestart: true, + }); + yield* switchTurn("attempt-claude-model-change-running-subagent-c"); + assert.lengthOf(processQueues, 2); + + yield* Queue.offer( + processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000903", + result: "Switched model.", + }), + ); + yield* changes.until(() => terminals().length === 2); + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make("attempt-claude-model-change-running-subagent-d"), + text: "Switch back.", + attachments: [], + providerTurnOrdinal: 3, + }), + ); + assert.lengthOf(processQueues, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); // regression: #20413 an unreadable append file must not tear down the running process it.effect("keeps the live process when its replacement cannot read the append file", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-append-replacement-", - }); - const appendFile = NodePath.join(cwd, "rules.md"); - yield* fileSystem.writeFileString(appendFile, "File sentinel\n"); - const processQueues: Array> = []; - let closes = 0; - const firstTurnTerminal = yield* Deferred.make(); - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: { - ...DEFAULT_CLAUDE_SETTINGS, - launchArgs: "--append-system-prompt-file rules.md", - }, - environment: {}, - attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-append-replacement-attachments-", - }), - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator: yield* IdAllocator.IdAllocatorV2, - continuationRequests: { offer: () => Effect.void }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.sync(() => { - closes += 1; - }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd, - }); - const threadId = ThreadId.make("thread-claude-append-replacement"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-append-replacement"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-append-replacement-", + }); + const appendFile = NodePath.join(cwd, "rules.md"); + yield* fileSystem.writeFileString(appendFile, "File sentinel\n"); + const processQueues: Array> = []; + let closes = 0; + const firstTurnTerminal = yield* Deferred.make(); + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: { + ...DEFAULT_CLAUDE_SETTINGS, + launchArgs: "--append-system-prompt-file rules.md", + }, + environment: {}, + attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-append-replacement-attachments-", + }), + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + continuationRequests: { offer: () => Effect.void }, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.sync(() => { + closes += 1; + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd, + }); + const threadId = ThreadId.make("thread-claude-append-replacement"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-append-replacement"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + event.type === "turn.terminal" + ? Deferred.succeed(firstTurnTerminal, undefined) + : Effect.void, + ), + Effect.forkScoped, + ); + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-append-replacement-a"), + text: "What is the sentinel?", + attachments: [], runtimePolicy, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - event.type === "turn.terminal" - ? Deferred.succeed(firstTurnTerminal, undefined) - : Effect.void, - ), - Effect.forkScoped, - ); - const now = yield* DateTime.now; + }), + ); + yield* Queue.offer( + processQueues[0]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a01", + result: "File sentinel", + }), + ); + yield* Deferred.await(firstTurnTerminal); - yield* runtime.startTurn( + yield* fileSystem.remove(appendFile); + // A thinking change cannot apply live, so this turn must replace the process. + const refused = yield* runtime + .startTurn( makeClaudeTestTurnInput({ threadId, - providerThread, + providerThread: { ...providerThread, status: "active" }, now, - attemptId: RunAttemptId.make("attempt-claude-append-replacement-a"), - text: "What is the sentinel?", + attemptId: RunAttemptId.make("attempt-claude-append-replacement-b"), + text: "Switch model.", attachments: [], + providerTurnOrdinal: 2, + modelSelection: CLAUDE_TEST_RESTART_MODEL_SELECTION, runtimePolicy, }), - ); - yield* Queue.offer( - processQueues[0]!, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000a01", - result: "File sentinel", - }), - ); - yield* Deferred.await(firstTurnTerminal); - - yield* fileSystem.remove(appendFile); - // A thinking change cannot apply live, so this turn must replace the process. - const refused = yield* runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-claude-append-replacement-b"), - text: "Switch model.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: CLAUDE_TEST_RESTART_MODEL_SELECTION, - runtimePolicy, - }), - ) - .pipe(Effect.flip); - assert.equal( - makeProviderFailure({ cause: refused, class: "provider_error" }).message, - new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({ path: appendFile }).message, - ); - assert.lengthOf(processQueues, 1); - assert.equal(closes, 0); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + ) + .pipe(Effect.flip); + assert.equal( + makeProviderFailure({ cause: refused, class: "provider_error" }).message, + new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({ path: appendFile }).message, + ); + assert.lengthOf(processQueues, 1); + assert.equal(closes, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), - ); - - it.effect( - "keeps the process and its roster when a model change meets a running background shell", - () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* makeChangeSignal; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-replace-open-fail-", - }); - let openCount = 0; - const processQueues: Array> = []; - const events: Array = []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - random: yield* SecureRandom.SecureRandom, - idAllocator, - continuationRequests: { - offer: () => Effect.void, - }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => { - openCount += 1; - if (openCount === 2) { - return Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "open", - cause: "forced replacement open failure", - }), - ); - } - return Effect.gen(function* () { - const sdkMessages = yield* Queue.unbounded(); - processQueues.push(sdkMessages); - return { - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }); - }, - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - subagentModel: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-replace-open-fail"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-replace-open-fail"), - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe(Effect.andThen(changes.notify)), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "Claude adapter runtime must expose hasPendingBackgroundWork.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const now = yield* DateTime.now; - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - assert.equal(processQueues.length, 1); - yield* Queue.offer(processQueues[0]!, wakeTaskStarted); - yield* Queue.offer(processQueues[0]!, turnOneResult); - yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); - assert.isTrue(yield* hasPendingBackgroundWork); - - const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; - const failedStart = yield* runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-b"), - text: "Replace process but fail open.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ) - .pipe(Effect.exit); - assert.isTrue(Exit.isFailure(failedStart)); - assert.equal(openCount, 1); - assert.isTrue(yield* hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - // regression: #26082 a killed Claude process names its signal on the failed turn - it.effect("names the signal that killed the Claude process on the failed turn", () => - Effect.scoped( + ); + + it.effect( + "keeps the process and its roster when a model change meets a running background shell", + () => Effect.gen(function* () { const changes = yield* makeChangeSignal; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-process-signal-", + prefix: "t3-claude-v2-replace-open-fail-", }); - const sdkMessages = yield* Queue.unbounded< - SDKMessage, - ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError - >(); + let openCount = 0; + const processQueues: Array> = []; const events: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, @@ -19994,34 +19845,51 @@ describe("ClaudeAdapterV2 background wake turns", () => { path: yield* Path.Path, random: yield* SecureRandom.SecureRandom, idAllocator, + continuationRequests: { + offer: () => Effect.void, + }, queryRunner: { allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.succeed({ - messages: Stream.fromQueue(sdkMessages), - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - mcpServerStatus: Effect.succeed([]), - readMcpResource: () => Effect.die("unexpected MCP resource read"), - callMcpTool: () => Effect.die("unexpected MCP tool call"), - listPermissionRules: Effect.die("unexpected permission rules read"), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }), + open: () => { + openCount += 1; + if (openCount === 2) { + return Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "open", + cause: "forced replacement open failure", + }), + ); + } + return Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processQueues.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; + }); + }, forkSession: () => Effect.die("unused forkSession"), subagentLaunchToolUseId: () => Effect.succeed(null), subagentModel: () => Effect.succeed(null), assertComplete: Effect.void, }, }); - const threadId = ThreadId.make("thread-claude-process-signal"); + const threadId = ThreadId.make("thread-claude-replace-open-fail"); const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-process-signal"), + providerSessionId: ProviderSessionId.make("provider-session-claude-replace-open-fail"), modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, }); @@ -20038,52 +19906,46 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), Effect.forkScoped, ); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Claude adapter runtime must expose hasPendingBackgroundWork."); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const now = yield* DateTime.now; + yield* runtime.startTurn( makeClaudeTestTurnInput({ threadId, providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-process-signal"), - text: "Write a long reply.", + now, + attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-a"), + text: "Run the build in the background.", attachments: [], }), ); - yield* Queue.offer( - sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000026082", - text: "Here is the first part", - }), - ); - // Mirrors ProcessTransport.getProcessExitError in @anthropic-ai/claude-agent-sdk. - const processExit = Object.assign( - new Error( - "Claude Code process terminated by signal SIGABRT. stderr: fork failed: Resource temporarily unavailable", - ), - { - telemetryMessage: "Claude Code process terminated by signal SIGABRT", - errorClass: "process_killed_by_signal", - signal: "SIGABRT", - }, - ); - yield* Queue.fail( - sdkMessages, - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "messages", - cause: processExit, - }), - ); - + assert.equal(processQueues.length, 1); + yield* Queue.offer(processQueues[0]!, wakeTaskStarted); + yield* Queue.offer(processQueues[0]!, turnOneResult); yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); - const terminal = events.find((event) => event.type === "turn.terminal"); - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.include( - terminal.failure.message, - "Claude Code process terminated by signal SIGABRT", - ); - assert.notInclude(terminal.failure.message, "stderr"); - assert.equal(terminal.failure.code, "process_killed_by_signal"); + assert.isTrue(yield* hasPendingBackgroundWork); + + const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; + const failedStart = yield* runtime + .startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread: { ...providerThread, status: "active" }, + now, + attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-b"), + text: "Replace process but fail open.", + attachments: [], + providerTurnOrdinal: 2, + modelSelection: alternateModel, + }), + ) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(failedStart)); + assert.equal(openCount, 1); + assert.isTrue(yield* hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -20094,6 +19956,127 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + // regression: #26082 a killed Claude process names its signal on the failed turn + it.effect("names the signal that killed the Claude process on the failed turn", () => + Effect.gen(function* () { + const changes = yield* makeChangeSignal; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-process-signal-", + }); + const sdkMessages = yield* Queue.unbounded< + SDKMessage, + ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError + >(); + const events: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), + open: () => + Effect.succeed({ + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-process-signal"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-process-signal"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe(Effect.andThen(changes.notify)), + ), + Effect.forkScoped, + ); + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-process-signal"), + text: "Write a long reply.", + attachments: [], + }), + ); + yield* Queue.offer( + sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000026082", + text: "Here is the first part", + }), + ); + // Mirrors ProcessTransport.getProcessExitError in @anthropic-ai/claude-agent-sdk. + const processExit = Object.assign( + new Error( + "Claude Code process terminated by signal SIGABRT. stderr: fork failed: Resource temporarily unavailable", + ), + { + telemetryMessage: "Claude Code process terminated by signal SIGABRT", + errorClass: "process_killed_by_signal", + signal: "SIGABRT", + }, + ); + yield* Queue.fail( + sdkMessages, + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "messages", + cause: processExit, + }), + ); + + yield* changes.until(() => events.some((event) => event.type === "turn.terminal")); + const terminal = events.find((event) => event.type === "turn.terminal"); + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.include(terminal.failure.message, "Claude Code process terminated by signal SIGABRT"); + assert.notInclude(terminal.failure.message, "stderr"); + assert.equal(terminal.failure.code, "process_killed_by_signal"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); @@ -20282,656 +20265,88 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* input.harness.offerAndWait(workflowToolUse); yield* input.harness.offerAndWait(workflowTaskStarted); yield* input.harness.offerAndWait(workflowLaunchAck(input.harness.transcriptDir)); - yield* input.harness.offerAndWait( - workflowSnapshot({ uuid: input.snapshotUuid, state: input.state ?? "start" }), - ); - yield* input.harness.until(() => workflowMemberEvents(input.harness.events, 2).length === 1); - }); - - it.effect.each(["Agent", "Workflow"] as const)( - "keeps a workflow running after its %s launch reply without an async flag", - (toolName) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-workflow-launch-${toolName}`), - text: "Run the workflow.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowToolUse, - message: { - model: "claude-sonnet-4-6", - content: [ - { type: "tool_use", id: WORKFLOW_TOOL_USE_ID, name: toolName, input: {} }, - ], - }, - }), - ); - yield* harness.offerAndWait(workflowTaskStarted); - yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001200", state: "start" }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001201", result: "Launched." }), - ); - yield* Queue.take(harness.terminalReceipts); - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, - "running", - ); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - const toolItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TOOL_USE_ID - ? [event.turnItem.status] - : [], - ); - assert.deepEqual(toolItems, toolName === "Workflow" ? ["running", "completed"] : []); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001202", - status: "completed", - }), - ); - yield* Queue.take(harness.continuationReceipts); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-workflow-complete-${toolName}`), - text: "Workflow finished.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001205", result: "Finished." }), - ); - yield* Queue.take(harness.terminalReceipts); - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, - "completed", - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, - "completed", - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); + yield* input.harness.offerAndWait( + workflowSnapshot({ uuid: input.snapshotUuid, state: input.state ?? "start" }), + ); + yield* input.harness.until(() => workflowMemberEvents(input.harness.events, 2).length === 1); + }); - it.effect("marks a workflow coordinator's script prompt and leaves a subagent brief plain", () => - Effect.scoped( + it.effect.each(["Agent", "Workflow"] as const)( + "keeps a workflow running after its %s launch reply without an async flag", + (toolName) => Effect.gen(function* () { const harness = yield* makeWorkflowHarness; - const script = - 'export const meta = { name: "probe-wf", description: "Run the alpha workflow" };'; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-script-prompt"), - text: "Run the workflow and an auditor.", + attemptId: RunAttemptId.make(`attempt-workflow-launch-${toolName}`), + text: "Run the workflow.", attachments: [], }), ); - yield* harness.offerAndWait(workflowToolUse); - yield* harness.offerAndWait(claudeSdkFrame({ ...workflowTaskStarted, prompt: script })); - yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001289", state: "start" }), - ); yield* harness.offerAndWait( claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: "task-plain-auditor", - description: "Audit recent commits", - task_type: "local_agent", - prompt: "Audit the last five commits.", - uuid: "00000000-0000-4000-8000-000000001290", - session_id: WAKE_NATIVE_SESSION, - }), - ); - const subagentPrompt = (nativeTaskId: string) => { - const subagent = harness.events.flatMap((event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === nativeTaskId - ? [event.subagent] - : [], - )[0]; - const message = threadMessages(harness.events, subagent?.childThreadId).find( - (event) => event.message.role === "user", - )?.message; - const turnItem = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "user_message" && - event.turnItem.messageId === message?.id, - ); - return { - text: message?.text, - messageMark: message?.workflowScript, - itemMark: - turnItem?.type === "turn_item.updated" && turnItem.turnItem.type === "user_message" - ? turnItem.turnItem.workflowScript - : undefined, - }; - }; - // The user message item lands after the subagent node, so wait on the item itself. - yield* harness.until( - () => - workflowCoordinatorEvents(harness.events).length > 0 && - subagentPrompt(WORKFLOW_TASK_ID).itemMark !== undefined && - subagentPrompt("task-plain-auditor").itemMark !== undefined, - ); - assert.deepEqual(subagentPrompt(WORKFLOW_TASK_ID), { - text: script, - messageMark: true, - itemMark: true, - }); - assert.deepEqual(subagentPrompt("task-plain-auditor"), { - text: "Audit the last five commits.", - messageMark: false, - itemMark: false, - }); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("stops only a live workflow task and waits for its stopped notification", () => - Effect.scoped( - Effect.gen(function* () { - const stoppedTasks: Array = []; - let interrupted = false; - let closed = false; - const harness = yield* makeWorkflowHarnessWithOptions({ - stopTask: (taskId) => - Effect.sync(() => { - stoppedTasks.push(taskId); - }), - interrupt: Effect.sync(() => { - interrupted = true; - }), - close: () => - Effect.sync(() => { - closed = true; - }), - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-stop"), - text: "Run the workflow.", - attachments: [], + ...workflowToolUse, + message: { + model: "claude-sonnet-4-6", + content: [{ type: "tool_use", id: WORKFLOW_TOOL_USE_ID, name: toolName, input: {} }], + }, }), ); - yield* harness.offerAndWait(workflowToolUse); yield* harness.offerAndWait(workflowTaskStarted); yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001100", - state: "start", - }), - ); - let member = yield* Queue.take(harness.subagentReceipts); - while (!member.subagent.nativeTaskRef?.nativeId?.endsWith(":agent:2")) { - member = yield* Queue.take(harness.subagentReceipts); - } - const stopTask = harness.runtime.stopTask!; - for (const taskId of ["missing-task", `${WORKFLOW_TASK_ID}:agent:1`]) { - const exit = yield* stopTask({ providerThread: harness.providerThread, taskId }).pipe( - Effect.exit, - ); - assert.isTrue(Exit.isFailure(exit)); - } - const wrongThread = { - ...harness.providerThread, - nativeThreadRef: { - driver: harness.providerThread.driver, - nativeId: "wrong-session", - strength: "strong" as const, - }, - }; - assert.isTrue( - Exit.isFailure( - yield* stopTask({ - providerThread: wrongThread, - taskId: WORKFLOW_TASK_ID, - }).pipe(Effect.exit), - ), - ); - assert.deepEqual(stoppedTasks, []); - yield* stopTask({ providerThread: harness.providerThread, taskId: WORKFLOW_TASK_ID }); - assert.deepEqual(stoppedTasks, [WORKFLOW_TASK_ID]); - assert.isFalse(interrupted); - assert.isFalse(closed); - assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "running"); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001101", - status: "stopped", - }), - ); - member = yield* Queue.take(harness.subagentReceipts); - while (!member.subagent.nativeTaskRef?.nativeId?.endsWith(":agent:2")) { - member = yield* Queue.take(harness.subagentReceipts); - } - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, - "cancelled", - ); - for (const index of [1, 2]) { - assert.equal( - workflowMemberEvents(harness.events, index).at(-1)?.subagent.status, - "cancelled", - ); - } - assert.isTrue( - Exit.isFailure( - yield* stopTask({ - providerThread: harness.providerThread, - taskId: WORKFLOW_TASK_ID, - }).pipe(Effect.exit), - ), - ); - assert.deepEqual(stoppedTasks, [WORKFLOW_TASK_ID]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("projects each workflow member as its own subagent thread", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - const now = yield* DateTime.now; - const coordinatorTurnItems = () => - harness.events.filter( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID, - ); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-workflow-members"), - text: "Run the alpha workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ - harness, - snapshotUuid: "00000000-0000-4000-8000-000000001004", - state: "queued", - }); - - const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent; - const first = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; - const second = workflowMemberEvents(harness.events, 2).at(-1)?.subagent; - assert.equal(first?.status, "pending"); - assert.isNull(first?.startedAt); - assert.equal(second?.status, "pending"); - assert.isNull(second?.startedAt); - const coordinatorThread = harness.events.find( - (event) => - event.type === "app_thread.created" && - event.appThread.id === coordinator?.childThreadId, - ); - assert.equal( - coordinatorThread?.type === "app_thread.created" - ? coordinatorThread.appThread.title - : null, - "Workflow · probe-wf", - ); - assert.equal(first?.title, "alpha:one"); - assert.equal(first?.prompt, "Reply with exactly: A1"); - assert.equal(first?.model, "claude-opus-5[1m]"); - assert.equal(first?.threadId, coordinator?.childThreadId); - assert.equal(second?.threadId, coordinator?.childThreadId); - assert.notEqual(first?.childThreadId, second?.childThreadId); - - assert.equal( - harness.events.find( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "app_thread.created" } - > => event.type === "app_thread.created" && event.appThread.id === first?.childThreadId, - )?.appThread.title, - "alpha:one", - ); - const memberNodes = harness.events.filter( - ( - event, - ): event is Extract => - event.type === "node.updated" && - event.node.nativeItemRef?.nativeId === first?.nativeTaskRef?.nativeId, - ); - assert.deepEqual( - memberNodes.map((event) => event.node.kind), - ["subagent", "root_turn"], - ); - assert.deepEqual( - memberNodes.map((event) => [event.node.status, event.node.startedAt]), - [ - ["pending", null], - ["pending", null], - ], - ); - assert.deepEqual( - threadMessages(harness.events, first?.childThreadId).map((event) => event.message.text), - ["Reply with exactly: A1"], - ); - assert.deepEqual( - threadMessages(harness.events, second?.childThreadId).map((event) => event.message.text), - ["Reply with exactly: A2"], - ); - - yield* TestClock.adjust("60 seconds"); - const memberStartedAt = DateTime.add(now, { seconds: 30 }); - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001007", - state: "start", - secondState: "queued", - startedAt: DateTime.toEpochMillis(memberStartedAt), - }), - ); - let started = yield* Queue.take(harness.subagentReceipts); - while (started.subagent.id !== first?.id || started.subagent.status !== "running") { - started = yield* Queue.take(harness.subagentReceipts); - } - assert.deepEqual(started.subagent.startedAt, memberStartedAt); - const startedRoot = harness.events.findLast( - (event) => event.type === "node.updated" && event.node.threadId === first?.childThreadId, - ); - assert.equal( - startedRoot?.type === "node.updated" ? startedRoot.node.status : null, - "running", - ); - assert.deepEqual( - startedRoot?.type === "node.updated" ? startedRoot.node.startedAt : null, - memberStartedAt, - ); - - const turnItemsBeforeRepeat = coordinatorTurnItems().length; - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001005", - state: "start", - secondState: "queued", - startedAt: DateTime.toEpochMillis(memberStartedAt), - }), - ); - yield* harness.until(() => coordinatorTurnItems().length > turnItemsBeforeRepeat); - assert.lengthOf(workflowMemberEvents(harness.events, 1), 2); - assert.lengthOf(workflowMemberEvents(harness.events, 2), 1); - - const firstThreadId = first?.childThreadId; - const firstThreadEvents = () => - harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "app_thread.created" } - > => event.type === "app_thread.created" && event.appThread.id === firstThreadId, - ); - const turnItemsBeforeMetadata = coordinatorTurnItems().length; - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001017", - state: "start", - secondState: "queued", - startedAt: DateTime.toEpochMillis(memberStartedAt), - label: "alpha:review", - prompt: "Review the change", - model: "claude-sonnet-4-6", - }), - ); - // The member's node and app thread pick up the metadata after the coordinator item. - yield* harness.until( - () => - coordinatorTurnItems().length > turnItemsBeforeMetadata && - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title === "alpha:review" && - firstThreadEvents().at(-1)?.appThread.title === "alpha:review", - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title, - "alpha:review", - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.prompt, - "Review the change", - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.model, - "claude-sonnet-4-6", - ); - assert.equal(firstThreadEvents().at(-1)?.appThread.title, "alpha:review"); - assert.equal( - firstThreadEvents().at(-1)?.appThread.modelSelection.model, - "claude-sonnet-4-6", - ); - assert.deepEqual( - firstThreadEvents().at(-1)?.appThread.createdAt, - firstThreadEvents()[0]?.appThread.createdAt, - ); - assert.equal( - threadMessages(harness.events, firstThreadId).at(-1)?.message.text, - "Review the change", - ); - - yield* TestClock.adjust("10 seconds"); - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001018", - state: "done", - secondState: "queued", - omitResult: true, - }), - ); - let finished = yield* Queue.take(harness.subagentReceipts); - while (finished.subagent.id !== first?.id || finished.subagent.status !== "completed") { - finished = yield* Queue.take(harness.subagentReceipts); - } - const completedAt = finished.subagent.completedAt; - assert.deepEqual(completedAt, DateTime.add(now, { seconds: 70 })); - yield* TestClock.adjust("60 seconds"); - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001019", - state: "done", - secondState: "queued", - }), - ); - let excerpt = yield* Queue.take(harness.subagentReceipts); - while (excerpt.subagent.id !== first?.id || excerpt.subagent.result !== "A1 excerpt") { - excerpt = yield* Queue.take(harness.subagentReceipts); - } - assert.deepEqual(excerpt.subagent.completedAt, completedAt); - const finishedRoot = harness.events.findLast( - (event) => event.type === "node.updated" && event.node.threadId === firstThreadId, - ); - assert.deepEqual( - finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined, - completedAt, - ); - - yield* harness.offerAndWait( - workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }), + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001200", state: "start" }), ); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001006", - result: "Launched the workflow.", - }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001201", result: "Launched." }), ); yield* Queue.take(harness.terminalReceipts); - const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent; - assert.equal(stopped?.status, "cancelled"); - assert.isNull(stopped?.startedAt); - const stoppedRoot = harness.events.findLast( - (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId, - ); - assert.equal( - stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null, - "cancelled", - ); - assert.isNull( - stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("projects workflow member threads after resuming a restarted session", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWorkflowHarnessWithOptions({ - subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID, - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-workflow-resume"), - text: "Continue the workflow.", - attachments: [], - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowToolUse, - message: { - model: "claude-sonnet-4-6", - content: [ - { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} }, - ], - }, - }), + assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "running"); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + const toolItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TOOL_USE_ID + ? [event.turnItem.status] + : [], ); + assert.deepEqual(toolItems, toolName === "Workflow" ? ["running", "completed"] : []); yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - tool_use_id: "toolu-resume-workflow", - prompt: "Continue the workflow.", + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000001202", + status: "completed", }), ); - yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }), + yield* Queue.take(harness.continuationReceipts); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-workflow-complete-${toolName}`), + text: "Workflow finished.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), ); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }), + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001205", result: "Finished." }), ); yield* Queue.take(harness.terminalReceipts); - const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; - const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent; - assert.isDefined(member); - assert.equal(member?.status, "running"); - assert.isTrue( - harness.events.some( - (event) => - event.type === "app_thread.created" && event.appThread.id === member?.childThreadId, - ), - ); - assert.deepEqual( - threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text), - ["Reply with exactly: A1", "A1 from the transcript"], - ); - assert.isDefined(coordinator?.childThreadId); - const recoveredThreads = harness.events.filter( - (event) => - event.type === "app_thread.created" && - event.appThread.id === coordinator?.childThreadId, - ); - assert.lengthOf(recoveredThreads, 1); - const recovered = recoveredThreads[0]; - assert.equal(recovered?.type, "app_thread.created"); - if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread"); - assert.isTrue(recovered.createOnly); - assert.deepEqual(recovered.appThread.lineage, { - parentThreadId: harness.threadId, - relationshipToParent: "subagent", - rootThreadId: harness.threadId, - }); - assert.equal(recovered.appThread.createdBy, "agent"); - assert.equal(recovered.appThread.creationSource, "provider"); - assert.isBelow( - harness.events.indexOf(recovered), - harness.events.findIndex( - (event) => - event.type === "subagent.updated" && - event.subagent.childThreadId === coordinator?.childThreadId, - ), + assert.equal( + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, + "completed", ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); + assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( @@ -20942,490 +20357,584 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("marks a workflow coordinator's script prompt and leaves a subagent brief plain", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + const script = + 'export const meta = { name: "probe-wf", description: "Run the alpha workflow" };'; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-script-prompt"), + text: "Run the workflow and an auditor.", + attachments: [], + }), + ); + yield* harness.offerAndWait(workflowToolUse); + yield* harness.offerAndWait(claudeSdkFrame({ ...workflowTaskStarted, prompt: script })); + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001289", state: "start" }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-plain-auditor", + description: "Audit recent commits", + task_type: "local_agent", + prompt: "Audit the last five commits.", + uuid: "00000000-0000-4000-8000-000000001290", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const subagentPrompt = (nativeTaskId: string) => { + const subagent = harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === nativeTaskId + ? [event.subagent] + : [], + )[0]; + const message = threadMessages(harness.events, subagent?.childThreadId).find( + (event) => event.message.role === "user", + )?.message; + const turnItem = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "user_message" && + event.turnItem.messageId === message?.id, + ); + return { + text: message?.text, + messageMark: message?.workflowScript, + itemMark: + turnItem?.type === "turn_item.updated" && turnItem.turnItem.type === "user_message" + ? turnItem.turnItem.workflowScript + : undefined, + }; + }; + // The user message item lands after the subagent node, so wait on the item itself. + yield* harness.until( + () => + workflowCoordinatorEvents(harness.events).length > 0 && + subagentPrompt(WORKFLOW_TASK_ID).itemMark !== undefined && + subagentPrompt("task-plain-auditor").itemMark !== undefined, + ); + assert.deepEqual(subagentPrompt(WORKFLOW_TASK_ID), { + text: script, + messageMark: true, + itemMark: true, + }); + assert.deepEqual(subagentPrompt("task-plain-auditor"), { + text: "Audit the last five commits.", + messageMark: false, + itemMark: false, + }); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); - it.effect.each([ - "root result", - "resume after root result", - "completion before buffered start", - ] as const)("orders %s arriving during workflow transcript replay", (arrival) => - Effect.scoped( - Effect.gen(function* () { - const digestStarted = yield* Deferred.make(); - const releaseDigest = yield* Deferred.make(); - const liveFrameOffered = yield* Deferred.make(); - let pauseDigest = false; - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarnessWithOptions({ close: Queue.shutdown }); - const taskId = "task-resumed-during-workflow-replay"; - const taskStart = (toolUseId: string, prompt: string, uuid: string) => - claudeSdkFrame({ - ...workflowTaskStarted, - task_id: taskId, - task_type: "local_agent", - is_backgrounded: true, - subagent_type: "general-purpose", - spawn_depth: 1, - workflow_name: undefined, - tool_use_id: toolUseId, - prompt, - uuid, - }); - const taskFinished = (toolUseId: string, summary: string, uuid: string) => - claudeSdkFrame({ - ...workflowNotification({ uuid, status: "completed" }), - task_id: taskId, - tool_use_id: toolUseId, - summary, - }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-replay-launch"), - text: "Run the workflow and a background subagent.", - attachments: [], - }), - ); - yield* harness.offerAndWait(workflowToolUse); - yield* harness.offerAndWait(workflowTaskStarted); - yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000003001", state: "start" }), - ); - if (arrival !== "completion before buffered start") { - yield* harness.offerAndWait( - taskStart("toolu-initial", "Initial work.", "00000000-0000-4000-8000-000000003002"), - ); - } - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000003003", - result: "Launched both tasks.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000003004", - status: "completed", - }), - ); - yield* Queue.take(harness.continuationReceipts); - if (arrival === "completion before buffered start") { - yield* harness.offerAndWait( - taskStart("toolu-initial", "Initial work.", "00000000-0000-4000-8000-000000003005"), - ); - } else { - yield* harness.offerAndWait( - taskFinished( - "toolu-initial", - "Initial result.", - "00000000-0000-4000-8000-000000003005", - ), - ); - } - if (arrival === "root result") { - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "init", - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000003006", - }), - ); - } - pauseDigest = true; - const replay = yield* harness.runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-replay-continuation"), - providerTurnOrdinal: 2, - text: "Continue.", - attachments: [], - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ) - .pipe(Effect.forkScoped); - yield* Deferred.await(digestStarted); - const liveFrames = yield* Effect.gen(function* () { - if (arrival === "completion before buffered start") { - yield* harness.offerAndWait( - taskFinished( - "toolu-initial", - "Initial result.", - "00000000-0000-4000-8000-000000003007", - ), - liveFrameOffered, - ); - return; - } - yield* harness.offerAndWait( - claudeSdkFrame({ - ...makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000003008", - result: "Native wake turn finished.", - }), - origin: { kind: "task-notification" }, - num_turns: 1, - }), - liveFrameOffered, - ); - if (arrival === "resume after root result") { - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "init", - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000003009", - }), - ); - yield* harness.offerAndWait( - taskStart( - "toolu-latest", - "Latest live resume.", - "00000000-0000-4000-8000-000000003010", - ), - ); - } - }).pipe(Effect.forkScoped); - yield* Deferred.await(liveFrameOffered); - yield* Deferred.succeed(releaseDigest, undefined); - yield* Fiber.join(replay); - yield* Fiber.join(liveFrames); - if (arrival === "resume after root result") { - yield* Queue.take(harness.terminalReceipts); - yield* Queue.take(harness.continuationReceipts); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-replay-resume-continuation"), - providerTurnOrdinal: 3, - text: "Continue.", - attachments: [], - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - } - if (arrival !== "root result") { - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000003011", - result: "Workflow answer delivered.", - }), - ); - } - yield* Queue.take(harness.terminalReceipts); - const latest = harness.events - .flatMap((event) => - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === taskId - ? [event.subagent] - : [], - ) - .at(-1); - if (arrival === "resume after root result") { - assert.equal(latest?.status, "running"); - assert.equal(latest?.prompt, "Latest live resume."); - assert.isNull(latest?.result); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - } else { - assert.equal(latest?.status, "completed"); - assert.equal(latest?.result, "Initial result."); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 1); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-replay-next-user"), - providerTurnOrdinal: 3, - text: "Next task.", - attachments: [], - }), - ); - } - }).pipe( - Effect.provideService(WorkflowAgentTranscriptReadObserver, () => - Effect.gen(function* () { - if (pauseDigest) { - pauseDigest = false; - yield* Deferred.succeed(digestStarted, undefined); - yield* Deferred.await(releaseDigest); - } - }), - ), + it.effect("stops only a live workflow task and waits for its stopped notification", () => + Effect.gen(function* () { + const stoppedTasks: Array = []; + let interrupted = false; + let closed = false; + const harness = yield* makeWorkflowHarnessWithOptions({ + stopTask: (taskId) => + Effect.sync(() => { + stoppedTasks.push(taskId); + }), + interrupt: Effect.sync(() => { + interrupted = true; + }), + close: () => + Effect.sync(() => { + closed = true; + }), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-stop"), + text: "Run the workflow.", + attachments: [], + }), + ); + yield* harness.offerAndWait(workflowToolUse); + yield* harness.offerAndWait(workflowTaskStarted); + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001100", + state: "start", + }), + ); + let member = yield* Queue.take(harness.subagentReceipts); + while (!member.subagent.nativeTaskRef?.nativeId?.endsWith(":agent:2")) { + member = yield* Queue.take(harness.subagentReceipts); + } + const stopTask = harness.runtime.stopTask!; + for (const taskId of ["missing-task", `${WORKFLOW_TASK_ID}:agent:1`]) { + const exit = yield* stopTask({ providerThread: harness.providerThread, taskId }).pipe( + Effect.exit, ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + assert.isTrue(Exit.isFailure(exit)); + } + const wrongThread = { + ...harness.providerThread, + nativeThreadRef: { + driver: harness.providerThread.driver, + nativeId: "wrong-session", + strength: "strong" as const, + }, + }; + assert.isTrue( + Exit.isFailure( + yield* stopTask({ + providerThread: wrongThread, + taskId: WORKFLOW_TASK_ID, + }).pipe(Effect.exit), + ), + ); + assert.deepEqual(stoppedTasks, []); + yield* stopTask({ providerThread: harness.providerThread, taskId: WORKFLOW_TASK_ID }); + assert.deepEqual(stoppedTasks, [WORKFLOW_TASK_ID]); + assert.isFalse(interrupted); + assert.isFalse(closed); + assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "running"); + yield* harness.offerAndWait( + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000001101", + status: "stopped", + }), + ); + member = yield* Queue.take(harness.subagentReceipts); + while (!member.subagent.nativeTaskRef?.nativeId?.endsWith(":agent:2")) { + member = yield* Queue.take(harness.subagentReceipts); + } + assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "cancelled"); + for (const index of [1, 2]) { + assert.equal( + workflowMemberEvents(harness.events, index).at(-1)?.subagent.status, + "cancelled", + ); + } + assert.isTrue( + Exit.isFailure( + yield* stopTask({ + providerThread: harness.providerThread, + taskId: WORKFLOW_TASK_ID, + }).pipe(Effect.exit), + ), + ); + assert.deepEqual(stoppedTasks, [WORKFLOW_TASK_ID]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("preserves buffered workflow outcomes when interrupted during replay", () => - Effect.scoped( - Effect.gen(function* () { - const digestStarted = yield* Deferred.make(); - const releaseDigest = yield* Deferred.make(); - let pauseDigest = false; - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarnessWithOptions({ close: Queue.shutdown }); - const secondTaskId = "task-workflow-buffered-completion"; - const secondToolUseId = "toolu-workflow-buffered-completion"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-buffered-launch"), - text: "Run both workflows.", - attachments: [], - }), - ); - yield* launchWorkflow({ - harness, - snapshotUuid: "00000000-0000-4000-8000-000000003100", - }); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - task_id: secondTaskId, - tool_use_id: secondToolUseId, - uuid: "00000000-0000-4000-8000-000000003101", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000003102", - state: "start", - }), - task_id: secondTaskId, - tool_use_id: secondToolUseId, - }), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000003103", - result: "Launched both workflows.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000003104", - status: "completed", - }), - ); - yield* Queue.take(harness.continuationReceipts); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowNotification({ - uuid: "00000000-0000-4000-8000-000000003105", - status: "completed", - }), - task_id: secondTaskId, - tool_use_id: secondToolUseId, - }), - ); - const continuationInput = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-buffered-replay"), - providerTurnOrdinal: 2, - text: "Continue.", - attachments: [], - messageCreatedBy: "agent", - messageCreationSource: "provider", - }); - pauseDigest = true; - const replay = yield* harness.runtime - .startTurn(continuationInput) - .pipe(Effect.forkScoped); - yield* Deferred.await(digestStarted); - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${continuationInput.attemptId}`, - }), - }); - yield* Deferred.succeed(releaseDigest, undefined); - yield* Fiber.join(replay); - const second = harness.events - .flatMap((event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === secondTaskId - ? [event.subagent] - : [], - ) - .at(-1); - assert.equal(second?.status, "completed"); - assert.equal(second?.result, "Workflow finished."); - }).pipe( - Effect.provideService(WorkflowAgentTranscriptReadObserver, () => - Effect.gen(function* () { - if (pauseDigest) { - pauseDigest = false; - yield* Deferred.succeed(digestStarted, undefined); - yield* Deferred.await(releaseDigest); - } - }), - ), + it.effect("projects each workflow member as its own subagent thread", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + const now = yield* DateTime.now; + const coordinatorTurnItems = () => + harness.events.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID, ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-workflow-members"), + text: "Run the alpha workflow.", + attachments: [], + }), + ); + yield* launchWorkflow({ + harness, + snapshotUuid: "00000000-0000-4000-8000-000000001004", + state: "queued", + }); + + const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent; + const first = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; + const second = workflowMemberEvents(harness.events, 2).at(-1)?.subagent; + assert.equal(first?.status, "pending"); + assert.isNull(first?.startedAt); + assert.equal(second?.status, "pending"); + assert.isNull(second?.startedAt); + const coordinatorThread = harness.events.find( + (event) => + event.type === "app_thread.created" && event.appThread.id === coordinator?.childThreadId, + ); + assert.equal( + coordinatorThread?.type === "app_thread.created" ? coordinatorThread.appThread.title : null, + "Workflow · probe-wf", + ); + assert.equal(first?.title, "alpha:one"); + assert.equal(first?.prompt, "Reply with exactly: A1"); + assert.equal(first?.model, "claude-opus-5[1m]"); + assert.equal(first?.threadId, coordinator?.childThreadId); + assert.equal(second?.threadId, coordinator?.childThreadId); + assert.notEqual(first?.childThreadId, second?.childThreadId); + + assert.equal( + harness.events.find( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "app_thread.created" } + > => event.type === "app_thread.created" && event.appThread.id === first?.childThreadId, + )?.appThread.title, + "alpha:one", + ); + const memberNodes = harness.events.filter( + ( + event, + ): event is Extract => + event.type === "node.updated" && + event.node.nativeItemRef?.nativeId === first?.nativeTaskRef?.nativeId, + ); + assert.deepEqual( + memberNodes.map((event) => event.node.kind), + ["subagent", "root_turn"], + ); + assert.deepEqual( + memberNodes.map((event) => [event.node.status, event.node.startedAt]), + [ + ["pending", null], + ["pending", null], + ], + ); + assert.deepEqual( + threadMessages(harness.events, first?.childThreadId).map((event) => event.message.text), + ["Reply with exactly: A1"], + ); + assert.deepEqual( + threadMessages(harness.events, second?.childThreadId).map((event) => event.message.text), + ["Reply with exactly: A2"], + ); + + yield* TestClock.adjust("60 seconds"); + const memberStartedAt = DateTime.add(now, { seconds: 30 }); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001007", + state: "start", + secondState: "queued", + startedAt: DateTime.toEpochMillis(memberStartedAt), + }), + ); + let started = yield* Queue.take(harness.subagentReceipts); + while (started.subagent.id !== first?.id || started.subagent.status !== "running") { + started = yield* Queue.take(harness.subagentReceipts); + } + assert.deepEqual(started.subagent.startedAt, memberStartedAt); + const startedRoot = harness.events.findLast( + (event) => event.type === "node.updated" && event.node.threadId === first?.childThreadId, + ); + assert.equal( + startedRoot?.type === "node.updated" ? startedRoot.node.status : null, + "running", + ); + assert.deepEqual( + startedRoot?.type === "node.updated" ? startedRoot.node.startedAt : null, + memberStartedAt, + ); + + const turnItemsBeforeRepeat = coordinatorTurnItems().length; + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001005", + state: "start", + secondState: "queued", + startedAt: DateTime.toEpochMillis(memberStartedAt), + }), + ); + yield* harness.until(() => coordinatorTurnItems().length > turnItemsBeforeRepeat); + assert.lengthOf(workflowMemberEvents(harness.events, 1), 2); + assert.lengthOf(workflowMemberEvents(harness.events, 2), 1); + + const firstThreadId = first?.childThreadId; + const firstThreadEvents = () => + harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "app_thread.created" } + > => event.type === "app_thread.created" && event.appThread.id === firstThreadId, + ); + const turnItemsBeforeMetadata = coordinatorTurnItems().length; + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001017", + state: "start", + secondState: "queued", + startedAt: DateTime.toEpochMillis(memberStartedAt), + label: "alpha:review", + prompt: "Review the change", + model: "claude-sonnet-4-6", + }), + ); + // The member's node and app thread pick up the metadata after the coordinator item. + yield* harness.until( + () => + coordinatorTurnItems().length > turnItemsBeforeMetadata && + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title === "alpha:review" && + firstThreadEvents().at(-1)?.appThread.title === "alpha:review", + ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title, "alpha:review"); + assert.equal( + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.prompt, + "Review the change", + ); + assert.equal( + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.model, + "claude-sonnet-4-6", + ); + assert.equal(firstThreadEvents().at(-1)?.appThread.title, "alpha:review"); + assert.equal(firstThreadEvents().at(-1)?.appThread.modelSelection.model, "claude-sonnet-4-6"); + assert.deepEqual( + firstThreadEvents().at(-1)?.appThread.createdAt, + firstThreadEvents()[0]?.appThread.createdAt, + ); + assert.equal( + threadMessages(harness.events, firstThreadId).at(-1)?.message.text, + "Review the change", + ); + + yield* TestClock.adjust("10 seconds"); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001018", + state: "done", + secondState: "queued", + omitResult: true, + }), + ); + let finished = yield* Queue.take(harness.subagentReceipts); + while (finished.subagent.id !== first?.id || finished.subagent.status !== "completed") { + finished = yield* Queue.take(harness.subagentReceipts); + } + const completedAt = finished.subagent.completedAt; + assert.deepEqual(completedAt, DateTime.add(now, { seconds: 70 })); + yield* TestClock.adjust("60 seconds"); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001019", + state: "done", + secondState: "queued", + }), + ); + let excerpt = yield* Queue.take(harness.subagentReceipts); + while (excerpt.subagent.id !== first?.id || excerpt.subagent.result !== "A1 excerpt") { + excerpt = yield* Queue.take(harness.subagentReceipts); + } + assert.deepEqual(excerpt.subagent.completedAt, completedAt); + const finishedRoot = harness.events.findLast( + (event) => event.type === "node.updated" && event.node.threadId === firstThreadId, + ); + assert.deepEqual( + finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined, + completedAt, + ); + + yield* harness.offerAndWait( + workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001006", + result: "Launched the workflow.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent; + assert.equal(stopped?.status, "cancelled"); + assert.isNull(stopped?.startedAt); + const stoppedRoot = harness.events.findLast( + (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId, + ); + assert.equal( + stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null, + "cancelled", + ); + assert.isNull(stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect.each([ - ["api_error", false, false], - ["aborted_streaming", false, false], - ["api_error", true, false], - ["api_error", false, true], - ["aborted_streaming", false, true], - ] as const)( - "stops the run's live workflow after root result %s, continuation=%s, pending Stop=%s", - ([terminalReason, continuation, pendingStop]) => - Effect.scoped( - Effect.gen(function* () { - const stoppedTasks: Array = []; - const stopRequested = yield* Deferred.make(); - const harness = yield* makeWorkflowHarnessWithOptions({ - stopTask: (taskId) => - Effect.sync(() => void stoppedTasks.push(taskId)).pipe( - Effect.andThen(Deferred.succeed(stopRequested, undefined)), - Effect.asVoid, - ), - }); - const now = yield* DateTime.now; - const turnInput = { - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-workflow-root-failure"), - text: "Run the workflow.", - attachments: [], - }; - yield* harness.runtime.startTurn(makeClaudeTestTurnInput(turnInput)); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001050" }); - const stopping = pendingStop - ? yield* harness.runtime.stopSubagent!({ - providerThread: harness.providerThread, - nativeTaskId: WORKFLOW_TASK_ID, - }).pipe(Effect.exit, Effect.forkScoped) - : undefined; - if (pendingStop) yield* Deferred.await(stopRequested); - if (continuation) { - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001051", - result: "Launched.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - uuid: "00000000-0000-4000-8000-000000001052", - }), - ); - } - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001053", - result: "Root turn ended.", - terminalReason, - isError: terminalReason === "api_error", - }), - ); - if (continuation) { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - ...turnInput, - attemptId: RunAttemptId.make("attempt-claude-workflow-root-failure-wake"), - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - } - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, terminalReason === "api_error" ? "failed" : "interrupted"); - assert.equal(terminal.threadDisposition, "reusable"); - const settled = terminalReason === "api_error" ? "failed" : "cancelled"; - assert.deepEqual( - stoppedTasks, - pendingStop ? [WORKFLOW_TASK_ID, WORKFLOW_TASK_ID] : [WORKFLOW_TASK_ID], - ); - if (stopping !== undefined) { - yield* TestClock.adjust("2 seconds"); - assert.isTrue(Exit.isFailure(yield* Fiber.join(stopping))); - const retry = yield* harness.runtime.stopSubagent!({ - providerThread: harness.providerThread, - nativeTaskId: WORKFLOW_TASK_ID, - }).pipe(Effect.exit, Effect.forkScoped); - yield* TestClock.adjust("2 seconds"); - assert.isTrue(Exit.isFailure(yield* Fiber.join(retry))); - } - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, settled); - for (const index of [1, 2]) { - assert.equal( - workflowMemberEvents(harness.events, index).at(-1)?.subagent.status, - settled, - ); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + it.effect("projects workflow member threads after resuming a restarted session", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarnessWithOptions({ + subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-workflow-resume"), + text: "Continue the workflow.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...workflowToolUse, + message: { + model: "claude-sonnet-4-6", + content: [ + { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} }, + ], + }, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...workflowTaskStarted, + tool_use_id: "toolu-resume-workflow", + prompt: "Continue the workflow.", + }), + ); + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }), + ); + yield* Queue.take(harness.terminalReceipts); + const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; + const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent; + assert.isDefined(member); + assert.equal(member?.status, "running"); + assert.isTrue( + harness.events.some( + (event) => + event.type === "app_thread.created" && event.appThread.id === member?.childThreadId, + ), + ); + assert.deepEqual( + threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text), + ["Reply with exactly: A1", "A1 from the transcript"], + ); + assert.isDefined(coordinator?.childThreadId); + const recoveredThreads = harness.events.filter( + (event) => + event.type === "app_thread.created" && event.appThread.id === coordinator?.childThreadId, + ); + assert.lengthOf(recoveredThreads, 1); + const recovered = recoveredThreads[0]; + assert.equal(recovered?.type, "app_thread.created"); + if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread"); + assert.isTrue(recovered.createOnly); + assert.deepEqual(recovered.appThread.lineage, { + parentThreadId: harness.threadId, + relationshipToParent: "subagent", + rootThreadId: harness.threadId, + }); + assert.equal(recovered.appThread.createdBy, "agent"); + assert.equal(recovered.appThread.creationSource, "provider"); + assert.isBelow( + harness.events.indexOf(recovered), + harness.events.findIndex( + (event) => + event.type === "subagent.updated" && + event.subagent.childThreadId === coordinator?.childThreadId, + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect("clears workflow member metadata only after a successful transcript read", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - const now = yield* DateTime.now; + it.effect.each([ + "root result", + "resume after root result", + "completion before buffered start", + ] as const)("orders %s arriving during workflow transcript replay", (arrival) => + Effect.gen(function* () { + const digestStarted = yield* Deferred.make(); + const releaseDigest = yield* Deferred.make(); + const liveFrameOffered = yield* Deferred.make(); + let pauseDigest = false; + yield* Effect.gen(function* () { + const harness = yield* makeWorkflowHarnessWithOptions({ close: Queue.shutdown }); + const taskId = "task-resumed-during-workflow-replay"; + const taskStart = (toolUseId: string, prompt: string, uuid: string) => + claudeSdkFrame({ + ...workflowTaskStarted, + task_id: taskId, + task_type: "local_agent", + is_backgrounded: true, + subagent_type: "general-purpose", + spawn_depth: 1, + workflow_name: undefined, + tool_use_id: toolUseId, + prompt, + uuid, + }); + const taskFinished = (toolUseId: string, summary: string, uuid: string) => + claudeSdkFrame({ + ...workflowNotification({ uuid, status: "completed" }), + task_id: taskId, + tool_use_id: toolUseId, + summary, + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-workflow-metadata"), - text: "Run the alpha workflow in the background.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-replay-launch"), + text: "Run the workflow and a background subagent.", attachments: [], }), ); @@ -21433,309 +20942,408 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* harness.offerAndWait(workflowTaskStarted); yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "done" }), + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000003001", state: "start" }), ); - yield* harness.until( - () => - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] - ?.effort === "xhigh", - ); - let coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; - assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); - - const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl"); - NodeFS.renameSync(transcriptPath, `${transcriptPath}.saved`); + if (arrival !== "completion before buffered start") { + yield* harness.offerAndWait( + taskStart("toolu-initial", "Initial work.", "00000000-0000-4000-8000-000000003002"), + ); + } yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001041", - state: "done", - label: "alpha:unreadable", + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003003", + result: "Launched both tasks.", }), ); - yield* harness.until( - () => - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] - ?.label === "alpha:unreadable", - ); - coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; - assert.equal(coordinator.workflow?.agents[0]?.effort, "xhigh"); - assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); - - NodeFS.renameSync(`${transcriptPath}.saved`, transcriptPath); - NodeFS.appendFileSync( - transcriptPath, - '{"type":"assistant","uuid":"wf-metadata-cleared","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_new","content":[{"type":"text","text":"New answer without metadata"}]}}\n', - ); + yield* Queue.take(harness.terminalReceipts); yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001042", - state: "done", - label: "alpha:new-response", + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000003004", + status: "completed", }), ); - yield* harness.until(() => { - const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow - ?.agents[0]; - return ( - member?.label === "alpha:new-response" && - member.effort === undefined && - member.speed === undefined + yield* Queue.take(harness.continuationReceipts); + if (arrival === "completion before buffered start") { + yield* harness.offerAndWait( + taskStart("toolu-initial", "Initial work.", "00000000-0000-4000-8000-000000003005"), ); - }); - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001043", result: "Done." }), - ); + } else { + yield* harness.offerAndWait( + taskFinished( + "toolu-initial", + "Initial result.", + "00000000-0000-4000-8000-000000003005", + ), + ); + } + if (arrival === "root result") { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "init", + session_id: WAKE_NATIVE_SESSION, + uuid: "00000000-0000-4000-8000-000000003006", + }), + ); + } + pauseDigest = true; + const replay = yield* harness.runtime + .startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-replay-continuation"), + providerTurnOrdinal: 2, + text: "Continue.", + attachments: [], + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(digestStarted); + const liveFrames = yield* Effect.gen(function* () { + if (arrival === "completion before buffered start") { + yield* harness.offerAndWait( + taskFinished( + "toolu-initial", + "Initial result.", + "00000000-0000-4000-8000-000000003007", + ), + liveFrameOffered, + ); + return; + } + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003008", + result: "Native wake turn finished.", + }), + origin: { kind: "task-notification" }, + num_turns: 1, + }), + liveFrameOffered, + ); + if (arrival === "resume after root result") { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "init", + session_id: WAKE_NATIVE_SESSION, + uuid: "00000000-0000-4000-8000-000000003009", + }), + ); + yield* harness.offerAndWait( + taskStart( + "toolu-latest", + "Latest live resume.", + "00000000-0000-4000-8000-000000003010", + ), + ); + } + }).pipe(Effect.forkScoped); + yield* Deferred.await(liveFrameOffered); + yield* Deferred.succeed(releaseDigest, undefined); + yield* Fiber.join(replay); + yield* Fiber.join(liveFrames); + if (arrival === "resume after root result") { + yield* Queue.take(harness.terminalReceipts); + yield* Queue.take(harness.continuationReceipts); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-replay-resume-continuation"), + providerTurnOrdinal: 3, + text: "Continue.", + attachments: [], + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + } + if (arrival !== "root result") { + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003011", + result: "Workflow answer delivered.", + }), + ); + } yield* Queue.take(harness.terminalReceipts); - const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow - ?.agents[0]; - assert.isUndefined(member?.effort); - assert.isUndefined(member?.speed); - const childThreadId = member?.childThreadId; - assert.deepEqual( - threadMessages(harness.events, childThreadId) - .filter((event) => event.message.role === "assistant") - .map((event) => event.message.text), - ["A1 from the transcript", "New answer without metadata"], - ); + const latest = harness.events + .flatMap((event) => + event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === taskId + ? [event.subagent] + : [], + ) + .at(-1); + if (arrival === "resume after root result") { + assert.equal(latest?.status, "running"); + assert.equal(latest?.prompt, "Latest live resume."); + assert.isNull(latest?.result); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + } else { + assert.equal(latest?.status, "completed"); + assert.equal(latest?.result, "Initial result."); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-replay-next-user"), + providerTurnOrdinal: 3, + text: "Next task.", + attachments: [], + }), + ); + } }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.provideService(WorkflowAgentTranscriptReadObserver, () => + Effect.gen(function* () { + if (pauseDigest) { + pauseDigest = false; + yield* Deferred.succeed(digestStarted, undefined); + yield* Deferred.await(releaseDigest); + } + }), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-workflow-settled"), - text: "Run the alpha workflow in the background.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001007" }); - const firstThreadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; - const secondThreadId = workflowMemberEvents(harness.events, 2)[0]?.subagent.childThreadId; - const currentAssistantAnswers = () => [ - ...new Map( - threadMessages(harness.events, firstThreadId) - .filter((event) => event.message.role === "assistant") - .map((event) => [event.message.id, event.message.text]), - ).values(), - ]; - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001008", - result: "Launched the workflow.", - }), - ); - yield* Queue.take(harness.terminalReceipts); + it.effect("preserves buffered workflow outcomes when interrupted during replay", () => + Effect.gen(function* () { + const digestStarted = yield* Deferred.make(); + const releaseDigest = yield* Deferred.make(); + let pauseDigest = false; + yield* Effect.gen(function* () { + const harness = yield* makeWorkflowHarnessWithOptions({ close: Queue.shutdown }); + const secondTaskId = "task-workflow-buffered-completion"; + const secondToolUseId = "toolu-workflow-buffered-completion"; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-unrelated-failure"), - text: "Do another task.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-buffered-launch"), + text: "Run both workflows.", attachments: [], - providerTurnOrdinal: 2, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001014", - result: "Another task failed.", - terminalReason: "api_error", - isError: true, }), ); - yield* Queue.take(harness.terminalReceipts); - assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "running"); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); - - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001009", state: "done" }), - ); - yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2); - - yield* harness.until( - () => - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] - ?.effort === "xhigh", - ); - const coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; - assert.deepEqual( - coordinator.workflow?.agents.map((member) => member.state), - ["completed", "completed"], - ); - assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); - assert.isUndefined(coordinator.workflow?.agents[1]?.effort); - assert.isUndefined(coordinator.workflow?.agents[1]?.speed); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); - assert.equal(workflowMemberEvents(harness.events, 2).at(-1)?.subagent.status, "completed"); - assert.deepEqual( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.completedAt, - yield* DateTime.now, - ); - assert.deepEqual( - threadMessages(harness.events, firstThreadId).map((event) => event.message.text), - ["Reply with exactly: A1", "A1 from the transcript"], - ); - assert.deepEqual( - threadMessages(harness.events, secondThreadId).map((event) => event.message.text), - ["Reply with exactly: A2", "Partial answer from workflow progress:\n\nA2 excerpt"], - ); - const coordinatorEventsBeforeRepeat = workflowCoordinatorEvents(harness.events).length; - const memberEventsBeforeRepeat = workflowMemberEvents(harness.events, 2).length; - NodeFS.appendFileSync( - NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - '{"type":"assistant","uuid":"wf-line-4","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n', - ); + yield* launchWorkflow({ + harness, + snapshotUuid: "00000000-0000-4000-8000-000000003100", + }); yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }), - ); - yield* harness.until( - () => workflowCoordinatorEvents(harness.events).length > coordinatorEventsBeforeRepeat, - ); - yield* harness.until( - () => - threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued", - ); - assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat); - assert.lengthOf(threadMessages(harness.events, secondThreadId), 2); - assert.deepEqual(currentAssistantAnswers(), ["A1 from the transcript", "A1 continued"]); - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a2.jsonl"), - '{"type":"assistant","uuid":"wf-line-5","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a2","content":[{"type":"text","text":"A2 from the transcript"}]}}\n', + claudeSdkFrame({ + ...workflowTaskStarted, + task_id: secondTaskId, + tool_use_id: secondToolUseId, + uuid: "00000000-0000-4000-8000-000000003101", + }), ); yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }), - ); - yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 3); - assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat); - assert.equal( - threadMessages(harness.events, secondThreadId).at(-1)?.message.text, - "A2 from the transcript", - ); - const previousStartedAt = workflowMemberEvents(harness.events, 1).at(-1)?.subagent - .startedAt; - yield* TestClock.adjust(1_000); - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - [ - '{"type":"assistant","uuid":"wf-line-6","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}', - '{"type":"assistant","uuid":"wf-line-7","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}', - ].join("\n") + "\n", + claudeSdkFrame({ + ...workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000003102", + state: "start", + }), + task_id: secondTaskId, + tool_use_id: secondToolUseId, + }), ); yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001018", - state: "done", - attempt: 2, - startedAt: 1000, - durationMs: 500, - lastProgressAt: 4432, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003103", + result: "Launched both workflows.", }), ); - yield* harness.until(() => - currentAssistantAnswers().join("\n\n").includes("Second answer"), - ); - assert.deepEqual(currentAssistantAnswers().slice(-2), ["First answer", "Second answer"]); - const completedMember = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; - assert.equal( - completedMember?.completedAt && DateTime.toEpochMillis(completedMember.completedAt), - 4432, - ); - assert.isUndefined( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.effort, - ); - assert.isUndefined( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.speed, - ); - assert.notDeepEqual( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt, - previousStartedAt, - ); + yield* Queue.take(harness.terminalReceipts); yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001019", - state: "start", - attempt: 3, + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000003104", + status: "completed", }), ); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); - assert.isNull(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.completedAt); - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001020", - state: "start", - attempt: 3, + yield* Queue.take(harness.continuationReceipts); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...workflowNotification({ + uuid: "00000000-0000-4000-8000-000000003105", + status: "completed", + }), + task_id: secondTaskId, + tool_use_id: secondToolUseId, }), ); - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - '{"type":"assistant","uuid":"wf-line-8","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n', - ); - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001021", - state: "done", - attempt: 3, + const continuationInput = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-workflow-buffered-replay"), + providerTurnOrdinal: 2, + text: "Continue.", + attachments: [], + messageCreatedBy: "agent", + messageCreationSource: "provider", + }); + pauseDigest = true; + const replay = yield* harness.runtime.startTurn(continuationInput).pipe(Effect.forkScoped); + yield* Deferred.await(digestStarted); + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${continuationInput.attemptId}`, }), - ); - yield* harness.until( - () => - threadMessages(harness.events, firstThreadId).at(-1)?.message.text === - "A1 retry answer", - ); - assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer"); - NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl")); - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001022", - state: "start", - attempt: 4, + }); + yield* Deferred.succeed(releaseDigest, undefined); + yield* Fiber.join(replay); + const second = harness.events + .flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === secondTaskId + ? [event.subagent] + : [], + ) + .at(-1); + assert.equal(second?.status, "completed"); + assert.equal(second?.result, "Workflow finished."); + }).pipe( + Effect.provideService(WorkflowAgentTranscriptReadObserver, () => + Effect.gen(function* () { + if (pauseDigest) { + pauseDigest = false; + yield* Deferred.succeed(digestStarted, undefined); + yield* Deferred.await(releaseDigest); + } }), - ); - yield* harness.until( - () => - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] - ?.attempt === 4, - ); - const answersBeforeEmptyAttempt = currentAssistantAnswers(); + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each([ + ["api_error", false, false], + ["aborted_streaming", false, false], + ["api_error", true, false], + ["api_error", false, true], + ["aborted_streaming", false, true], + ] as const)( + "stops the run's live workflow after root result %s, continuation=%s, pending Stop=%s", + ([terminalReason, continuation, pendingStop]) => + Effect.gen(function* () { + const stoppedTasks: Array = []; + const stopRequested = yield* Deferred.make(); + const harness = yield* makeWorkflowHarnessWithOptions({ + stopTask: (taskId) => + Effect.sync(() => void stoppedTasks.push(taskId)).pipe( + Effect.andThen(Deferred.succeed(stopRequested, undefined)), + Effect.asVoid, + ), + }); + const now = yield* DateTime.now; + const turnInput = { + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-workflow-root-failure"), + text: "Run the workflow.", + attachments: [], + }; + yield* harness.runtime.startTurn(makeClaudeTestTurnInput(turnInput)); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001050" }); + const stopping = pendingStop + ? yield* harness.runtime.stopSubagent!({ + providerThread: harness.providerThread, + nativeTaskId: WORKFLOW_TASK_ID, + }).pipe(Effect.exit, Effect.forkScoped) + : undefined; + if (pendingStop) yield* Deferred.await(stopRequested); + if (continuation) { + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001051", + result: "Launched.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...workflowTaskStarted, + uuid: "00000000-0000-4000-8000-000000001052", + }), + ); + } yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001023", - state: "done", - attempt: 4, - omitResult: true, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001053", + result: "Root turn ended.", + terminalReason, + isError: terminalReason === "api_error", }), ); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); + if (continuation) { + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + ...turnInput, + attemptId: RunAttemptId.make("attempt-claude-workflow-root-failure-wake"), + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + } + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, terminalReason === "api_error" ? "failed" : "interrupted"); + assert.equal(terminal.threadDisposition, "reusable"); + const settled = terminalReason === "api_error" ? "failed" : "cancelled"; assert.deepEqual( - currentAssistantAnswers(), - answersBeforeEmptyAttempt, - "an attempt with no transcript and no excerpt adds nothing", + stoppedTasks, + pendingStop ? [WORKFLOW_TASK_ID, WORKFLOW_TASK_ID] : [WORKFLOW_TASK_ID], ); + if (stopping !== undefined) { + yield* TestClock.adjust("2 seconds"); + assert.isTrue(Exit.isFailure(yield* Fiber.join(stopping))); + const retry = yield* harness.runtime.stopSubagent!({ + providerThread: harness.providerThread, + nativeTaskId: WORKFLOW_TASK_ID, + }).pipe(Effect.exit, Effect.forkScoped); + yield* TestClock.adjust("2 seconds"); + assert.isTrue(Exit.isFailure(yield* Fiber.join(retry))); + } + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, settled); + for (const index of [1, 2]) { + assert.equal( + workflowMemberEvents(harness.events, index).at(-1)?.subagent.status, + settled, + ); + } }).pipe( Effect.provide( Layer.mergeAll( @@ -21746,6 +21354,330 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ), + ); + + it.effect("clears workflow member metadata only after a successful transcript read", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-workflow-metadata"), + text: "Run the alpha workflow in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(workflowToolUse); + yield* harness.offerAndWait(workflowTaskStarted); + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir)); + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "done" }), + ); + yield* harness.until( + () => + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.effort === + "xhigh", + ); + let coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; + assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); + + const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl"); + NodeFS.renameSync(transcriptPath, `${transcriptPath}.saved`); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001041", + state: "done", + label: "alpha:unreadable", + }), + ); + yield* harness.until( + () => + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.label === + "alpha:unreadable", + ); + coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; + assert.equal(coordinator.workflow?.agents[0]?.effort, "xhigh"); + assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); + + NodeFS.renameSync(`${transcriptPath}.saved`, transcriptPath); + NodeFS.appendFileSync( + transcriptPath, + '{"type":"assistant","uuid":"wf-metadata-cleared","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_new","content":[{"type":"text","text":"New answer without metadata"}]}}\n', + ); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001042", + state: "done", + label: "alpha:new-response", + }), + ); + yield* harness.until(() => { + const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow + ?.agents[0]; + return ( + member?.label === "alpha:new-response" && + member.effort === undefined && + member.speed === undefined + ); + }); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001043", result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + const member = workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]; + assert.isUndefined(member?.effort); + assert.isUndefined(member?.speed); + const childThreadId = member?.childThreadId; + assert.deepEqual( + threadMessages(harness.events, childThreadId) + .filter((event) => event.message.role === "assistant") + .map((event) => event.message.text), + ["A1 from the transcript", "New answer without metadata"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-workflow-settled"), + text: "Run the alpha workflow in the background.", + attachments: [], + }), + ); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001007" }); + const firstThreadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; + const secondThreadId = workflowMemberEvents(harness.events, 2)[0]?.subagent.childThreadId; + const currentAssistantAnswers = () => [ + ...new Map( + threadMessages(harness.events, firstThreadId) + .filter((event) => event.message.role === "assistant") + .map((event) => [event.message.id, event.message.text]), + ).values(), + ]; + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001008", + result: "Launched the workflow.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-unrelated-failure"), + text: "Do another task.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000001014", + result: "Another task failed.", + terminalReason: "api_error", + isError: true, + }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, "running"); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); + + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001009", state: "done" }), + ); + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2); + + yield* harness.until( + () => + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.effort === + "xhigh", + ); + const coordinator = workflowCoordinatorEvents(harness.events).at(-1)!.subagent; + assert.deepEqual( + coordinator.workflow?.agents.map((member) => member.state), + ["completed", "completed"], + ); + assert.equal(coordinator.workflow?.agents[0]?.speed, "standard"); + assert.isUndefined(coordinator.workflow?.agents[1]?.effort); + assert.isUndefined(coordinator.workflow?.agents[1]?.speed); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); + assert.equal(workflowMemberEvents(harness.events, 2).at(-1)?.subagent.status, "completed"); + assert.deepEqual( + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.completedAt, + yield* DateTime.now, + ); + assert.deepEqual( + threadMessages(harness.events, firstThreadId).map((event) => event.message.text), + ["Reply with exactly: A1", "A1 from the transcript"], + ); + assert.deepEqual( + threadMessages(harness.events, secondThreadId).map((event) => event.message.text), + ["Reply with exactly: A2", "Partial answer from workflow progress:\n\nA2 excerpt"], + ); + const coordinatorEventsBeforeRepeat = workflowCoordinatorEvents(harness.events).length; + const memberEventsBeforeRepeat = workflowMemberEvents(harness.events, 2).length; + NodeFS.appendFileSync( + NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), + '{"type":"assistant","uuid":"wf-line-4","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n', + ); + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }), + ); + yield* harness.until( + () => workflowCoordinatorEvents(harness.events).length > coordinatorEventsBeforeRepeat, + ); + yield* harness.until( + () => threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued", + ); + assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat); + assert.lengthOf(threadMessages(harness.events, secondThreadId), 2); + assert.deepEqual(currentAssistantAnswers(), ["A1 from the transcript", "A1 continued"]); + NodeFS.writeFileSync( + NodePath.join(harness.transcriptDir, "agent-a2.jsonl"), + '{"type":"assistant","uuid":"wf-line-5","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a2","content":[{"type":"text","text":"A2 from the transcript"}]}}\n', + ); + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }), + ); + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 3); + assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat); + assert.equal( + threadMessages(harness.events, secondThreadId).at(-1)?.message.text, + "A2 from the transcript", + ); + const previousStartedAt = workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt; + yield* TestClock.adjust(1_000); + NodeFS.writeFileSync( + NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), + [ + '{"type":"assistant","uuid":"wf-line-6","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}', + '{"type":"assistant","uuid":"wf-line-7","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}', + ].join("\n") + "\n", + ); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001018", + state: "done", + attempt: 2, + startedAt: 1000, + durationMs: 500, + lastProgressAt: 4432, + }), + ); + yield* harness.until(() => currentAssistantAnswers().join("\n\n").includes("Second answer")); + assert.deepEqual(currentAssistantAnswers().slice(-2), ["First answer", "Second answer"]); + const completedMember = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; + assert.equal( + completedMember?.completedAt && DateTime.toEpochMillis(completedMember.completedAt), + 4432, + ); + assert.isUndefined( + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.effort, + ); + assert.isUndefined( + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]?.speed, + ); + assert.notDeepEqual( + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt, + previousStartedAt, + ); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001019", + state: "start", + attempt: 3, + }), + ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running"); + assert.isNull(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.completedAt); + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001020", + state: "start", + attempt: 3, + }), + ); + NodeFS.writeFileSync( + NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), + '{"type":"assistant","uuid":"wf-line-8","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n', + ); + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001021", + state: "done", + attempt: 3, + }), + ); + yield* harness.until( + () => + threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 retry answer", + ); + assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer"); + NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl")); + yield* Queue.offer( + harness.sdkMessages, + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001022", + state: "start", + attempt: 4, + }), + ); + yield* harness.until( + () => + workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] + ?.attempt === 4, + ); + const answersBeforeEmptyAttempt = currentAssistantAnswers(); + yield* harness.offerAndWait( + workflowSnapshot({ + uuid: "00000000-0000-4000-8000-000000001023", + state: "done", + attempt: 4, + omitResult: true, + }), + ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); + assert.deepEqual( + currentAssistantAnswers(), + answersBeforeEmptyAttempt, + "an attempt with no transcript and no excerpt adds nothing", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); @@ -21832,289 +21764,276 @@ describe("ClaudeAdapterV2 background wake turns", () => { : `${item.type} ${item.status}`; it.effect("streams a running workflow member's conversation from its transcript", () => - Effect.scoped( - Effect.gen(function* () { - const reads: Array<{ - readonly startOffset: number; - readonly endOffset: number; - readonly lineCount: number; - }> = []; - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl"); - NodeFS.writeFileSync(transcriptPath, memberTranscript); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-workflow-live-stream"), - text: "Run the alpha workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" }); - const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; - const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" }); - - assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ - "user_message", - "reasoning: List the files first.", - "command completed: README.md", - "assistant_message", - ]); - assert.deepEqual( - threadMessages(harness.events, threadId).map((event) => event.message.text), - ["Reply with exactly: A1", "A1 found README.md"], - ); - assert.deepEqual(reads.at(-1), { - startOffset: 0, - endOffset: Buffer.byteLength(memberTranscript), - lineCount: 5, - }); - - const itemsBefore = memberThreadItems(harness.events, threadId).length; - const more = memberAssistantLine("line-more", "msg_a1_more", [ - { - type: "tool_use", - id: "toolu_a1_cat", - name: "Bash", - input: { command: "cat README.md" }, - }, - ]); - const half = memberToolResultLine("line-cat-result", "toolu_a1_cat", "hello"); - NodeFS.appendFileSync(transcriptPath, more + half.slice(0, 40)); - yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361")); - assert.deepEqual(reads.at(-1), { - startOffset: Buffer.byteLength(memberTranscript), - endOffset: Buffer.byteLength(memberTranscript + more), - lineCount: 1, - }); - assert.deepEqual( - memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem), - ["command running: "], - "only the new line is projected; the half-written one waits", - ); - - NodeFS.appendFileSync(transcriptPath, half.slice(40)); - yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362")); - assert.deepEqual(reads.at(-1), { - startOffset: Buffer.byteLength(memberTranscript + more), - endOffset: Buffer.byteLength(memberTranscript + more + half), - lineCount: 1, - }); - assert.deepEqual( - memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem), - ["command running: ", "command completed: hello"], - ); - - const itemsBeforeIdle = memberThreadItems(harness.events, threadId).length; - yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363")); - assert.equal(reads.at(-1)?.lineCount, 0); - assert.lengthOf(memberThreadItems(harness.events, threadId), itemsBeforeIdle); - - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }), - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, - "completed", - ); - assert.deepEqual( - threadMessages(harness.events, threadId).map((event) => event.message.text), - ["Reply with exactly: A1", "A1 found README.md"], - "the settled member adds no second copy of its answer", - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }), - ); - yield* Queue.take(harness.terminalReceipts); - }).pipe( - Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => - Effect.sync(() => { - if (read.agentId === "a1") { - reads.push({ - startOffset: read.startOffset, - endOffset: read.endOffset, - lineCount: read.lineCount, - }); - } - }), - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("interrupts the open tool calls of a workflow member that failed", () => - Effect.scoped( - Effect.gen(function* () { + Effect.gen(function* () { + const reads: Array<{ + readonly startOffset: number; + readonly endOffset: number; + readonly lineCount: number; + }> = []; + yield* Effect.gen(function* () { const harness = yield* makeWorkflowHarness; - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - memberAssistantLine("line-bash", "msg_a1", [ - { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } }, - ]), - ); + const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl"); + NodeFS.writeFileSync(transcriptPath, memberTranscript); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-workflow-member-fails"), + attemptId: RunAttemptId.make("attempt-claude-workflow-live-stream"), text: "Run the alpha workflow.", attachments: [], }), ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001370" }); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" }); const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; + const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" }); + assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ "user_message", - "command running: ", + "reasoning: List the files first.", + "command completed: README.md", + "assistant_message", ]); - yield* harness.offerAndWait( - workflowNotification({ uuid: "00000000-0000-4000-8000-000000001371", status: "failed" }), + assert.deepEqual( + threadMessages(harness.events, threadId).map((event) => event.message.text), + ["Reply with exactly: A1", "A1 found README.md"], ); - assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "failed"); - assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ - "user_message", - "command interrupted: ", + assert.deepEqual(reads.at(-1), { + startOffset: 0, + endOffset: Buffer.byteLength(memberTranscript), + lineCount: 5, + }); + + const itemsBefore = memberThreadItems(harness.events, threadId).length; + const more = memberAssistantLine("line-more", "msg_a1_more", [ + { + type: "tool_use", + id: "toolu_a1_cat", + name: "Bash", + input: { command: "cat README.md" }, + }, ]); + const half = memberToolResultLine("line-cat-result", "toolu_a1_cat", "hello"); + NodeFS.appendFileSync(transcriptPath, more + half.slice(0, 40)); + yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361")); + assert.deepEqual(reads.at(-1), { + startOffset: Buffer.byteLength(memberTranscript), + endOffset: Buffer.byteLength(memberTranscript + more), + lineCount: 1, + }); + assert.deepEqual( + memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem), + ["command running: "], + "only the new line is projected; the half-written one waits", + ); + + NodeFS.appendFileSync(transcriptPath, half.slice(40)); + yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362")); + assert.deepEqual(reads.at(-1), { + startOffset: Buffer.byteLength(memberTranscript + more), + endOffset: Buffer.byteLength(memberTranscript + more + half), + lineCount: 1, + }); + assert.deepEqual( + memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem), + ["command running: ", "command completed: hello"], + ); + + const itemsBeforeIdle = memberThreadItems(harness.events, threadId).length; + yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363")); + assert.equal(reads.at(-1)?.lineCount, 0); + assert.lengthOf(memberThreadItems(harness.events, threadId), itemsBeforeIdle); + + yield* harness.offerAndWait( + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }), + ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed"); + assert.deepEqual( + threadMessages(harness.events, threadId).map((event) => event.message.text), + ["Reply with exactly: A1", "A1 found README.md"], + "the settled member adds no second copy of its answer", + ); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001372", result: "Done." }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }), ); yield* Queue.take(harness.terminalReceipts); }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => + Effect.sync(() => { + if (read.agentId === "a1") { + reads.push({ + startOffset: read.startOffset, + endOffset: read.endOffset, + lineCount: read.lineCount, + }); + } + }), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("interrupts the open tool calls of a workflow member that failed", () => + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + NodeFS.writeFileSync( + NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), + memberAssistantLine("line-bash", "msg_a1", [ + { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } }, + ]), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-workflow-member-fails"), + text: "Run the alpha workflow.", + attachments: [], + }), + ); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001370" }); + const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; + assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ + "user_message", + "command running: ", + ]); + yield* harness.offerAndWait( + workflowNotification({ uuid: "00000000-0000-4000-8000-000000001371", status: "failed" }), + ); + assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "failed"); + assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ + "user_message", + "command interrupted: ", + ]); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001372", result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect("reads a settled workflow member's transcript to its end past the read cap", () => - Effect.scoped( - Effect.gen(function* () { + Effect.gen(function* () { + const harness = yield* makeWorkflowHarness; + // Exceeds the launch and settle reads combined, at 512 KB each. + const filler = "x".repeat(16 * 1024); + NodeFS.writeFileSync( + NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), + Array.from({ length: 80 }, (_, index) => + memberAssistantLine(`line-early-${index}`, `msg_early_${index}`, [ + { type: "text", text: `${index} ${filler}` }, + ]), + ).join("") + + memberAssistantLine("line-final", "msg_final", [{ type: "text", text: "FINAL ANSWER" }]), + ); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-workflow-member-long-transcript"), + text: "Run the alpha workflow.", + attachments: [], + }), + ); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001390" }); + const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; + yield* harness.offerAndWait( + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000001391", + status: "completed", + }), + ); + const texts = threadMessages(harness.events, threadId) + .filter((event) => event.message.role === "assistant") + .map((event) => event.message.text); + assert.lengthOf(texts, 81); + assert.equal(texts.at(-1), "FINAL ANSWER", "the answer past the first read is shown"); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001392", result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("re-reads a workflow member's transcript after a restart without new items", () => + Effect.gen(function* () { + const runOnce = Effect.fnUntraced(function* (attemptId: string) { const harness = yield* makeWorkflowHarness; - // Exceeds the launch and settle reads combined, at 512 KB each. - const filler = "x".repeat(16 * 1024); NodeFS.writeFileSync( NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - Array.from({ length: 80 }, (_, index) => - memberAssistantLine(`line-early-${index}`, `msg_early_${index}`, [ - { type: "text", text: `${index} ${filler}` }, - ]), - ).join("") + - memberAssistantLine("line-final", "msg_final", [ - { type: "text", text: "FINAL ANSWER" }, - ]), + memberTranscript, ); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-workflow-member-long-transcript"), + attemptId: RunAttemptId.make(attemptId), text: "Run the alpha workflow.", attachments: [], }), ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001390" }); + yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001380" }); const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001391", - status: "completed", - }), - ); - const texts = threadMessages(harness.events, threadId) - .filter((event) => event.message.role === "assistant") - .map((event) => event.message.text); - assert.lengthOf(texts, 81); - assert.equal(texts.at(-1), "FINAL ANSWER", "the answer past the first read is shown"); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001392", result: "Done." }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001381", result: "Done." }), ); yield* Queue.take(harness.terminalReceipts); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - it.effect("re-reads a workflow member's transcript after a restart without new items", () => - Effect.scoped( - Effect.gen(function* () { - const runOnce = Effect.fnUntraced(function* (attemptId: string) { - const harness = yield* makeWorkflowHarness; - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a1.jsonl"), - memberTranscript, - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(attemptId), - text: "Run the alpha workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001380" }); - const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId; - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001381", result: "Done." }), - ); - yield* Queue.take(harness.terminalReceipts); - assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ - "user_message", - "reasoning: List the files first.", - "command completed: README.md", - "assistant_message", - ]); - return new Set(memberThreadItems(harness.events, threadId).map((item) => item.id)); - }); - const before = yield* runOnce("attempt-claude-workflow-before-restart"); - const after = yield* runOnce("attempt-claude-workflow-after-restart"); - assert.isAtLeast(before.size, 4); - assert.deepEqual( - [...after].filter((id) => !before.has(id)), - [], - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [ + "user_message", + "reasoning: List the files first.", + "command completed: README.md", + "assistant_message", + ]); + return new Set(memberThreadItems(harness.events, threadId).map((item) => item.id)); + }); + const before = yield* runOnce("attempt-claude-workflow-before-restart"); + const after = yield* runOnce("attempt-claude-workflow-after-restart"); + assert.isAtLeast(before.size, 4); + assert.deepEqual( + [...after].filter((id) => !before.has(id)), + [], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 59a8081589f90..e47560b7167af 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -83,6 +83,7 @@ import { mcpAppToolResourceUri, } from "@t3tools/shared/mcpApp"; import { AgentScope } from "@t3tools/shared/AgentScope"; +import * as ProviderProcesses from "../../process/providerProcesses.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model"; import { compareSemverVersions } from "@t3tools/shared/semver"; @@ -374,7 +375,10 @@ const CLAUDE_DESCENDANT_POLL = "1 second"; const CLAUDE_ROOT_REFUSAL = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; +// fd 4 gates the launch until the server has recorded the process it is about to become. const CLAUDE_GROUP_WATCH_SCRIPT = [ + "read -r _ <&4 || exit 1", + "exec 4<&-", "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", 'exec "$@" 3<&-', ].join("\n"); @@ -382,13 +386,15 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [ /** * Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for * setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on - * EOF from a pipe only this server holds, including when the server crashes. + * EOF from a pipe only this server holds, including when the server crashes. `register` records + * the CLI before it may run, so a restarted server can reap it if the watcher did not. */ export function spawnClaudeProcessGroup( options: ClaudeSpawnOptions, onExit?: () => void, onStderr: (text: string) => void = () => {}, onStderrClose: () => void = () => {}, + register?: (pid: number) => () => void, ): ClaudeSpawnedProcess & Pick { const child = NodeChildProcess.spawn( "/bin/sh", @@ -397,18 +403,34 @@ export function spawnClaudeProcessGroup( cwd: options.cwd, env: options.env, signal: options.signal, - stdio: ["pipe", "pipe", "pipe", "pipe"], + stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"], detached: true, }, ); + let forget: (() => void) | undefined; // Always drained, so a chatty CLI never blocks on a full stderr pipe. child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose); child.once("exit", () => { try { signalProcessGroup(child.pid ?? 0, "SIGKILL"); } catch {} + try { + forget?.(); + } catch {} onExit?.(); }); + const gate = child.stdio[4]; + if (child.pid !== undefined && gate !== null && gate !== undefined && "end" in gate) { + try { + forget = register?.(child.pid); + gate.on("error", () => child.kill("SIGKILL")); + gate.end("ready\n"); + } catch (cause) { + child.kill("SIGKILL"); + gate.destroy(); + throw cause; + } + } // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes. return child as ClaudeSpawnedProcess & Pick; } @@ -1258,6 +1280,7 @@ export const layerQueryRunner: Layer.Layer< const path = yield* Path.Path; const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers; const agentScope = yield* AgentScope; + const providerProcesses = yield* ProviderProcesses.ProviderProcesses; const platform = yield* HostProcess.Platform; const runFork = Effect.runForkWith(yield* Effect.context()); const hostEnvironment = yield* HostProcess.Environment; @@ -1374,6 +1397,7 @@ export const layerQueryRunner: Layer.Layer< stopScope, appendStderr, stderrDone, + providerProcesses.register, ); if (unit === undefined && child.pid !== undefined) { const tracker = trackDescendants(child.pid); @@ -2614,12 +2638,15 @@ export function makeClaudeUserMessage(input: { readonly text: string; readonly priority?: SDKUserMessage["priority"]; readonly skills?: ReadonlyMap; + readonly skillMentionsFrom?: number; readonly uuid?: SDKUserMessage["uuid"]; }): SDKUserMessage { // Claude expands a skill only when `/name` starts the last text block. // Keep the whole request before that block; see ClaudeSkillDispatch. const dispatch = - input.skills === undefined ? undefined : planClaudeSkillDispatch(input.text, input.skills); + input.skills === undefined + ? undefined + : planClaudeSkillDispatch(input.text, input.skills, input.skillMentionsFrom); // Claude runs `/goal` only when it opens the prompt, so a goal stays one block. const isGoalCommand = parseGoalCommand({ text: input.text }) !== null; return { @@ -2784,11 +2811,15 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: readonly fileSystem: FileSystem.FileSystem; readonly pdfReservation: Effect.Success>; readonly skills?: ReadonlyMap; + readonly skillMentionsFrom?: number; }) { if (input.attachments.length === 0) { const message = makeClaudeUserMessage({ text: input.text, ...(input.skills === undefined ? {} : { skills: input.skills }), + ...(input.skillMentionsFrom === undefined + ? {} + : { skillMentionsFrom: input.skillMentionsFrom }), ...(input.priority === undefined ? {} : { priority: input.priority }), ...(input.uuid === undefined ? {} : { uuid: input.uuid }), }); @@ -2812,7 +2843,7 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: const dispatch = input.skills === undefined ? undefined - : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills); + : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills, input.skillMentionsFrom); const content: Array = []; // Base64 adds a third to the payload. Leave room below Anthropic's 32 MB // request limit for text, instructions, and SDK framing. The SDK does not @@ -9341,31 +9372,41 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message.type === "system" && message.subtype === "task_started" && (yield* Ref.get(sessionSubagentsByTaskId)).has(message.task_id); + // A completed subagent that Claude resumes on its own (under its launch + // call, unlike SendMessage) has no live run left to show it while the + // root is idle; only a continuation does. + let isResumedSubagentTaskStarted = false; if ( isKnownSubagentTaskStarted && message.type === "system" && message.subtype === "task_started" ) { const now = yield* DateTime.now; - yield* Ref.update(sessionSubagentsByTaskId, (current) => { - const registered = current.get(message.task_id); - if (registered === undefined || registered.task.status === "running") { - return current; - } - const { progress: _staleProgress, ...priorTask } = registered.task; - return new Map(current).set(message.task_id, { - ...registered, - confirmedOutcome: undefined, - task: { - ...priorTask, - status: "running", - result: null, - startedAt: now, - completedAt: null, - updatedAt: now, - }, - }); - }); + isResumedSubagentTaskStarted = yield* Ref.modify( + sessionSubagentsByTaskId, + (current) => { + const registered = current.get(message.task_id); + if (registered === undefined || registered.task.status === "running") { + return [false, current] as const; + } + const { progress: _staleProgress, ...priorTask } = registered.task; + return [ + registered.runToolUseId === message.tool_use_id, + new Map(current).set(message.task_id, { + ...registered, + confirmedOutcome: undefined, + task: { + ...priorTask, + status: "running", + result: null, + startedAt: now, + completedAt: null, + updatedAt: now, + }, + }), + ] as const; + }, + ); } const isWakeTurnStart = isClaudeTurnStartMessage(message); const isWakeEvidence = @@ -9480,6 +9521,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( parentToolUseIdFromSdkMessage(message) === null; if ( !isPendingSubagentNotification && + !isResumedSubagentTaskStarted && !isNativeOpaqueWakeFrame && !isWakeTurnStart && message.type !== "result" @@ -12533,15 +12575,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( pdfBudgets.get(nativeThreadId)!, persistAttachmentBudget(nativeThreadId), ); + const promptText = applyClaudePromptEffortPrefix( + turnInput.message.text, + compileClaudeModelSelection(turnInput.modelSelection, modelCatalog).promptEffort, + ); const userMessage = promptUuid === null ? null : yield* makeClaudeUserMessageWithAttachments({ - text: applyClaudePromptEffortPrefix( - turnInput.message.text, - compileClaudeModelSelection(turnInput.modelSelection, modelCatalog) - .promptEffort, - ), + text: promptText, + // Mentions in inline handoff history are history, not this turn's skill. + ...(turnInput.inlineContextLength === undefined + ? {} + : { + skillMentionsFrom: + promptText.length - + turnInput.message.text.slice(turnInput.inlineContextLength).trimEnd() + .length, + }), attachments: turnInput.message.attachments, attachmentsDir, fileSystem, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 4716ec06175a6..3aca32bf41f90 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -232,70 +232,68 @@ const resumedMcpQueryInput = { } satisfies ClaudeAgentSdkQueryOpenInput; it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () => - Effect.scoped( - Effect.gen(function* () { - const registrationStarted = Promise.withResolvers(); - const disposalStarted = Promise.withResolvers(); - const finishDisposal = Promise.withResolvers(); - const prompts: AsyncIterable[] = []; - const firstClose = vi.fn(); - const secondClose = vi.fn(); - const firstRegistration = vi.fn(() => { - registrationStarted.resolve(); - return new Promise(() => {}); - }); - const secondRegistration = vi.fn(async () => ({ - added: ["t3-code"], - removed: [], - errors: {}, - })); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => { - assert.notTypeOf(prompt, "string"); - if (typeof prompt === "string") throw new Error("Expected streaming input"); - prompts.push(prompt); - return { - initializationResult: async () => ({}), - setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, - close: prompts.length === 1 ? firstClose : secondClose, - [Symbol.asyncDispose]: async () => { - firstClose(); - disposalStarted.resolve(); - await finishDisposal.promise; - }, - } as unknown as ClaudeSdk.Query; - }); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); - yield* Effect.promise(() => registrationStarted.promise); - yield* TestClock.adjust("90 seconds"); - yield* Effect.promise(() => disposalStarted.promise); - assert.equal(querySpy.mock.calls.length, 1); - finishDisposal.resolve(); - const session = yield* Fiber.join(opening); - yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); - - assert.equal(firstClose.mock.calls.length, 1); - assert.equal(secondClose.mock.calls.length, 0); - assert.equal(querySpy.mock.calls.length, 2); - for (const [call] of querySpy.mock.calls) { - assert.equal(call.options?.resume, FORK_SESSION_ID); - assert.isUndefined(call.options?.mcpServers); - } - assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]); - const message = { - type: "user", - message: { role: "user", content: "Continue where you left off." }, - parent_tool_use_id: null, - session_id: FORK_SESSION_ID, - } satisfies ClaudeSdk.SDKUserMessage; - yield* session.offer(message); - assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done); - const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next()); - assert.deepEqual(delivered.value, message); - assert.isFalse(delivered.done); - }).pipe(Effect.provide(realQueryRunner)), - ), + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposalStarted = Promise.withResolvers(); + const finishDisposal = Promise.withResolvers(); + const prompts: AsyncIterable[] = []; + const firstClose = vi.fn(); + const secondClose = vi.fn(); + const firstRegistration = vi.fn(() => { + registrationStarted.resolve(); + return new Promise(() => {}); + }); + const secondRegistration = vi.fn(async () => ({ + added: ["t3-code"], + removed: [], + errors: {}, + })); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => { + assert.notTypeOf(prompt, "string"); + if (typeof prompt === "string") throw new Error("Expected streaming input"); + prompts.push(prompt); + return { + initializationResult: async () => ({}), + setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, + close: prompts.length === 1 ? firstClose : secondClose, + [Symbol.asyncDispose]: async () => { + firstClose(); + disposalStarted.resolve(); + await finishDisposal.promise; + }, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => disposalStarted.promise); + assert.equal(querySpy.mock.calls.length, 1); + finishDisposal.resolve(); + const session = yield* Fiber.join(opening); + yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); + + assert.equal(firstClose.mock.calls.length, 1); + assert.equal(secondClose.mock.calls.length, 0); + assert.equal(querySpy.mock.calls.length, 2); + for (const [call] of querySpy.mock.calls) { + assert.equal(call.options?.resume, FORK_SESSION_ID); + assert.isUndefined(call.options?.mcpServers); + } + assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]); + const message = { + type: "user", + message: { role: "user", content: "Continue where you left off." }, + parent_tool_use_id: null, + session_id: FORK_SESSION_ID, + } satisfies ClaudeSdk.SDKUserMessage; + yield* session.offer(message); + assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done); + const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next()); + assert.deepEqual(delivered.value, message); + assert.isFalse(delivered.done); + }).pipe(Effect.provide(realQueryRunner)), ); it.effect.each([ @@ -303,262 +301,248 @@ it.effect.each([ { case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false }, { case: "a reply without a rule list", response: {}, readable: false }, ])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) => - Effect.scoped( - Effect.gen(function* () { - const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }]; - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - close: vi.fn(), - request: async () => ({ - response: - "response" in testCase - ? testCase.response - : { state: { rules, errors: testCase.errors } }, - }), - }) as unknown as ClaudeSdk.Query, - ); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options; - const session = yield* runner.open({ ...resumedMcpQueryInput, options }); - yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); - const exit = yield* Effect.exit(session.listPermissionRules); - if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules)); - else assert.isTrue(Exit.isFailure(exit)); - }).pipe(Effect.provide(realQueryRunner)), - ), + Effect.gen(function* () { + const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }]; + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + close: vi.fn(), + request: async () => ({ + response: + "response" in testCase + ? testCase.response + : { state: { rules, errors: testCase.errors } }, + }), + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options; + const session = yield* runner.open({ ...resumedMcpQueryInput, options }); + yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); + const exit = yield* Effect.exit(session.listPermissionRules); + if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules)); + else assert.isTrue(Exit.isFailure(exit)); + }).pipe(Effect.provide(realQueryRunner)), ); it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) => - Effect.scoped( - Effect.gen(function* () { - const registrationStarted = Promise.withResolvers(); - const cleanupProgress = Promise.withResolvers<"kill" | "retry">(); - const events = new NodeEvents.EventEmitter(); - const stdin = new NodeStream.PassThrough(); - const stdout = new NodeStream.PassThrough(); - const child = { - stdin, - stdout, - killed: false, - exitCode: null, - kill: vi.fn(() => { - cleanupProgress.resolve("kill"); - return true; - }), - on: events.on.bind(events), - once: events.once.bind(events), - off: events.off.bind(events), - } satisfies ClaudeSdk.SpawnedProcess; - const signal = yield* Effect.abortSignal; - const disposed = vi.fn(async () => {}); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { - const first = querySpy.mock.calls.length === 1; - if (first) { - options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal }); - } else { - cleanupProgress.resolve("retry"); - } - return { + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const cleanupProgress = Promise.withResolvers<"kill" | "retry">(); + const events = new NodeEvents.EventEmitter(); + const stdin = new NodeStream.PassThrough(); + const stdout = new NodeStream.PassThrough(); + const child = { + stdin, + stdout, + killed: false, + exitCode: null, + kill: vi.fn(() => { + cleanupProgress.resolve("kill"); + return true; + }), + on: events.on.bind(events), + once: events.once.bind(events), + off: events.off.bind(events), + } satisfies ClaudeSdk.SpawnedProcess; + const signal = yield* Effect.abortSignal; + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { + const first = querySpy.mock.calls.length === 1; + if (first) { + options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal }); + } else { + cleanupProgress.resolve("retry"); + } + return { + initializationResult: async () => ({}), + setMcpServers: () => { + registrationStarted.resolve(); + return first + ? new Promise(() => {}) + : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); + }, + close: vi.fn(), + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + querySpy.mockRestore(); + stdin.destroy(); + stdout.destroy(); + }), + ); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child }, + }) + .pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + + assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill"); + assert.equal(querySpy.mock.calls.length, 1); + assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]); + if (exits) events.emit("exit", null, "SIGKILL"); + else yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(opening); + assert.equal(Exit.isSuccess(result), exits); + if (Exit.isSuccess(result)) yield* result.value.close; + assert.equal(querySpy.mock.calls.length, exits ? 2 : 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), +); + +it.effect("stops retrying MCP registration after two timeouts and reports the cause", () => + Effect.gen(function* () { + const firstRegistration = Promise.withResolvers(); + const secondRegistration = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { + const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; + return { + initializationResult: async () => ({}), + setMcpServers: () => { + started.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => firstRegistration.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => secondRegistration.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.equal(querySpy.mock.calls.length, 2); + assert.equal(disposed.mock.calls.length, 2); + assert.equal( + makeProviderFailure({ + cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, + }).message, + "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.", + ); + }).pipe(Effect.provide(realQueryRunner)), +); + +it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () => + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ initializationResult: async () => ({}), setMcpServers: () => { registrationStarted.resolve(); - return first - ? new Promise(() => {}) - : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); + return new Promise(() => {}); }, - close: vi.fn(), [Symbol.asyncDispose]: disposed, - } as unknown as ClaudeSdk.Query; - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => { - querySpy.mockRestore(); - stdin.destroy(); - stdout.destroy(); - }), - ); - const runner = yield* ClaudeAgentSdkQueryRunner; - const opening = yield* runner - .open({ - ...resumedMcpQueryInput, - options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child }, - }) - .pipe(Effect.exit, Effect.forkChild); - yield* Effect.promise(() => registrationStarted.promise); - yield* TestClock.adjust("90 seconds"); - - assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill"); - assert.equal(querySpy.mock.calls.length, 1); - assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]); - if (exits) events.emit("exit", null, "SIGKILL"); - else yield* TestClock.adjust("10 seconds"); - const result = yield* Fiber.join(opening); - assert.equal(Exit.isSuccess(result), exits); - if (Exit.isSuccess(result)) yield* result.value.close; - assert.equal(querySpy.mock.calls.length, exits ? 2 : 1); - assert.equal(disposed.mock.calls.length, 1); - }).pipe(Effect.provide(realQueryRunner)), - ), + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* Fiber.interrupt(opening); + + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + const prompt = querySpy.mock.calls[0]![0].prompt; + if (typeof prompt === "string") throw new Error("Expected streaming input"); + assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done); + }).pipe(Effect.provide(realQueryRunner)), ); -it.effect("stops retrying MCP registration after two timeouts and reports the cause", () => - Effect.scoped( - Effect.gen(function* () { - const firstRegistration = Promise.withResolvers(); - const secondRegistration = Promise.withResolvers(); - const disposed = vi.fn(async () => {}); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { - const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; - return { +it.effect("does not reuse a fresh session ID after MCP registration times out", () => + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ initializationResult: async () => ({}), setMcpServers: () => { - started.resolve(); + registrationStarted.resolve(); return new Promise(() => {}); }, [Symbol.asyncDispose]: disposed, - } as unknown as ClaudeSdk.Query; - }); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const opening = yield* runner - .open(resumedMcpQueryInput) - .pipe(Effect.result, Effect.forkChild); - yield* Effect.promise(() => firstRegistration.promise); - yield* TestClock.adjust("90 seconds"); - yield* Effect.promise(() => secondRegistration.promise); - yield* TestClock.adjust("90 seconds"); - const result = yield* Fiber.join(opening); - - assert.equal(result._tag, "Failure"); - if (result._tag !== "Failure") return; - assert.equal(querySpy.mock.calls.length, 2); - assert.equal(disposed.mock.calls.length, 2); - assert.equal( - makeProviderFailure({ - cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, - }).message, - "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.", - ); - }).pipe(Effect.provide(realQueryRunner)), - ), -); - -it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () => - Effect.scoped( - Effect.gen(function* () { - const registrationStarted = Promise.withResolvers(); - const disposed = vi.fn(async () => {}); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: async () => ({}), - setMcpServers: () => { - registrationStarted.resolve(); - return new Promise(() => {}); - }, - [Symbol.asyncDispose]: disposed, - }) as unknown as ClaudeSdk.Query, - ); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); - yield* Effect.promise(() => registrationStarted.promise); - yield* Fiber.interrupt(opening); - - assert.equal(querySpy.mock.calls.length, 1); - assert.equal(disposed.mock.calls.length, 1); - const prompt = querySpy.mock.calls[0]![0].prompt; - if (typeof prompt === "string") throw new Error("Expected streaming input"); - assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done); - }).pipe(Effect.provide(realQueryRunner)), - ), -); - -it.effect("does not reuse a fresh session ID after MCP registration times out", () => - Effect.scoped( - Effect.gen(function* () { - const registrationStarted = Promise.withResolvers(); - const disposed = vi.fn(async () => {}); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: async () => ({}), - setMcpServers: () => { - registrationStarted.resolve(); - return new Promise(() => {}); - }, - [Symbol.asyncDispose]: disposed, - }) as unknown as ClaudeSdk.Query, - ); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const { resume, ...options } = resumedMcpQueryInput.options; - const opening = yield* runner - .open({ - ...resumedMcpQueryInput, - options: { ...options, sessionId: resume }, - }) - .pipe(Effect.result, Effect.forkChild); - yield* Effect.promise(() => registrationStarted.promise); - yield* TestClock.adjust("90 seconds"); - const result = yield* Fiber.join(opening); - - assert.equal(result._tag, "Failure"); - assert.equal(querySpy.mock.calls.length, 1); - assert.equal(disposed.mock.calls.length, 1); - }).pipe(Effect.provide(realQueryRunner)), - ), + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { resume, ...options } = resumedMcpQueryInput.options; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...options, sessionId: resume }, + }) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), ); it.effect.each([ ["opens after a slow CLI boot", "120 seconds", true], ["times out a CLI that never boots", "5 minutes", false], ] as const)("%s", ([, bootWait, boots]) => - Effect.scoped( - Effect.gen(function* () { - const waiting = Promise.withResolvers(); - const booted = Promise.withResolvers(); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: () => { - waiting.resolve(); - return booted.promise; - }, - // The CLI answers control requests only after it has booted. - setMcpServers: async () => { - waiting.resolve(); - await booted.promise; - return { added: ["t3-code"], removed: [], errors: {} }; - }, - close: vi.fn(), - [Symbol.asyncDispose]: async () => {}, - }) as unknown as ClaudeSdk.Query, + Effect.gen(function* () { + const waiting = Promise.withResolvers(); + const booted = Promise.withResolvers(); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + initializationResult: () => { + waiting.resolve(); + return booted.promise; + }, + // The CLI answers control requests only after it has booted. + setMcpServers: async () => { + waiting.resolve(); + await booted.promise; + return { added: ["t3-code"], removed: [], errors: {} }; + }, + close: vi.fn(), + [Symbol.asyncDispose]: async () => {}, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { resume, ...options } = resumedMcpQueryInput.options; + const opening = yield* runner + .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } }) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => waiting.promise); + yield* TestClock.adjust(bootWait); + if (boots) booted.resolve(); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, boots ? "Success" : "Failure"); + if (result._tag === "Success") yield* result.success.close; + else + assert.equal( + makeProviderFailure({ + cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, + }).message, + "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.", ); - yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); - const runner = yield* ClaudeAgentSdkQueryRunner; - const { resume, ...options } = resumedMcpQueryInput.options; - const opening = yield* runner - .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } }) - .pipe(Effect.result, Effect.forkChild); - yield* Effect.promise(() => waiting.promise); - yield* TestClock.adjust(bootWait); - if (boots) booted.resolve(); - const result = yield* Fiber.join(opening); - - assert.equal(result._tag, boots ? "Success" : "Failure"); - if (result._tag === "Success") yield* result.success.close; - else - assert.equal( - makeProviderFailure({ - cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, - }).message, - "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.", - ); - }).pipe(Effect.provide(realQueryRunner)), - ), + }).pipe(Effect.provide(realQueryRunner)), ); function fakeClaudeCli(script: string): string { @@ -764,6 +748,47 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }), ); + // A restarted server reaps recorded CLIs, so a CLI must never run before its record exists. + it.effect("records the CLI before it runs and forgets it once it exits", () => + Effect.gen(function* () { + const cli = fakeClaudeCli( + ['dir=$(dirname "$0")', 'printf \'%s %s\' "$$" "$(cat "$dir/record")" > "$dir/seen"'].join( + "\n", + ), + ); + const dir = NodePath.dirname(cli); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "seen")]); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), + ); + const forgotten = yield* Deferred.make(); + let registered = 0; + spawnClaudeProcessGroup( + { + command: cli, + args: [], + cwd: dir, + env: process.env, + // @effect-diagnostics-next-line abortControllerInEffect:off - The CLI exits on its own. + signal: new AbortController().signal, + }, + undefined, + undefined, + undefined, + (pid) => { + registered = pid; + NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid)); + return () => Deferred.doneUnsafe(forgotten, Effect.void); + }, + ); + const seen = yield* Effect.promise(() => + NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"), + ); + assert.equal(seen, `${registered} ${registered}`); + yield* Deferred.await(forgotten); + }), + ); + it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => { let runningAgents = 0; let releaseAgent!: () => void; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts index a1a4212326868..51c9a7848f100 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts @@ -101,33 +101,31 @@ describe("tailClaudeTaskOutput", () => { ).pipe(Effect.provide(NodeServices.layer)), ); - it.live("reads what was written last when the tool result stops it", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const { root, tasks, file } = yield* makeTaskFile; - yield* fileSystem.makeDirectory(tasks, { recursive: true }); - yield* fileSystem.writeFileString(file, "one\n"); - const chunks: Array = []; - const stop = yield* Deferred.make(); - const first = yield* Deferred.make(); - const fiber = yield* tailClaudeTaskOutput({ - root, - sessionId: SESSION_ID, - taskId: TASK_ID, - stop, - onChunk: (chunk) => - Effect.sync(() => chunks.push(chunk)).pipe( - Effect.andThen(Deferred.succeed(first, undefined)), - ), - }).pipe(Effect.forkScoped); - yield* Deferred.await(first); - yield* fileSystem.writeFileString(file, "one\ntwo\n"); - yield* Deferred.succeed(stop, undefined); - yield* Fiber.join(fiber); - assert.deepEqual(chunks, ["one\n", "two\n"]); - }).pipe(Effect.provide(NodeServices.layer)), - ), + it.effect("reads what was written last when the tool result stops it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const { root, tasks, file } = yield* makeTaskFile; + yield* fileSystem.makeDirectory(tasks, { recursive: true }); + yield* fileSystem.writeFileString(file, "one\n"); + const chunks: Array = []; + const stop = yield* Deferred.make(); + const first = yield* Deferred.make(); + const fiber = yield* tailClaudeTaskOutput({ + root, + sessionId: SESSION_ID, + taskId: TASK_ID, + stop, + onChunk: (chunk) => + Effect.sync(() => chunks.push(chunk)).pipe( + Effect.andThen(Deferred.succeed(first, undefined)), + ), + }).pipe(Effect.forkScoped); + yield* Deferred.await(first); + yield* fileSystem.writeFileString(file, "one\ntwo\n"); + yield* Deferred.succeed(stop, undefined); + yield* Fiber.join(fiber); + assert.deepEqual(chunks, ["one\n", "two\n"]); + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 818f28274bf19..ac0dc97166cdd 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -310,7 +310,6 @@ describe("CodexAdapterV2 native protocol logging", () => { const providerSessionId = ProviderSessionId.make("provider-session-1"); const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({ nativeEventLogger: logger, - threadId, providerSessionId, }); @@ -319,12 +318,52 @@ describe("CodexAdapterV2 native protocol logging", () => { return; } + const startThread = (requestId: number, appThreadId: string, nativeThreadId: string) => + Effect.gen(function* () { + yield* protocolLogger({ + direction: "outgoing", + stage: "decoded", + payload: { + id: requestId, + method: "thread/start", + params: { config: { "shell_environment_policy.set.T3CODE_THREAD_ID": appThreadId } }, + }, + }); + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { id: requestId, result: { thread: { id: nativeThreadId } } }, + }); + }); + yield* startThread(1, "thread-1", "native-1"); + yield* startThread(2, "thread-2", "native-2"); + yield* protocolLogger({ + direction: "outgoing", + stage: "decoded", + payload: { id: 3, method: "turn/start", params: { threadId: "native-2" } }, + }); + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { id: 3, result: { turn: { id: "turn-2" } } }, + }); + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { id: 4, result: { userAgent: "codex/1.0.0" } }, + }); + assert.deepEqual( + writes.splice(0).map((write) => write.threadId), + ["thread-1", "thread-1", "thread-2", "thread-2", "thread-2", "thread-2", null], + ); + yield* protocolLogger({ direction: "incoming", stage: "decoded", payload: { method: "thread/event", params: { + threadId: "native-1", id: "evt-1", http_headers: { Authorization: "Bearer secret-codex-token" }, usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, @@ -351,6 +390,7 @@ describe("CodexAdapterV2 native protocol logging", () => { payload: { method: "thread/event", params: { + threadId: "native-1", id: "evt-1", http_headers: { Authorization: "[REDACTED]" }, usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, @@ -1890,7 +1930,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); }).pipe(Effect.provide(CodexReplay.layerReplayWithDriver(driver))); } - }).pipe(Effect.scoped), + }), ); it.effect("waits for native start before interrupting an acknowledged queued turn", () => @@ -2211,55 +2251,351 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect("keeps an asynchronous Codex question actionable after the turn completes", () => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "async-question-thread"; - const nativeTurnId = "async-question-turn"; - const usage = { - totalTokens: 15, + Effect.gen(function* () { + const nativeThreadId = "async-question-thread"; + const nativeTurnId = "async-question-turn"; + const usage = { + totalTokens: 15, + inputTokens: 10, + cachedInputTokens: 2, + outputTokens: 5, + reasoningOutputTokens: 1, + }; + const transcript = makeCodexReplayTranscript({ + scenario: "async-question-and-billed-usage", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "Continue while I decide.", + }), + { + type: "emit_inbound", + label: "question", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + item: { + type: "agentMessage", + id: "async-question-item", + text: "Which branch?", + delivery: "async", + questions: [{ title: "Which branch?", options: ["main", "dev"] }], + }, + }, + }, + }, + { + type: "emit_inbound", + label: "usage", + frame: { + method: "thread/tokenUsage/updated", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, + }, + }, + }, + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("async-question-attempt"), + text: "Continue while I decide.", + }), + ); + yield* harness.firstTerminal; + const requests = harness.events.flatMap((event) => + event.type === "runtime_request.updated" ? [event.runtimeRequest] : [], + ); + assert.lengthOf(requests, 1); + assert.equal(requests[0]?.status, "pending"); + assert.deepEqual(requests[0]?.responseCapability, { type: "message" }); + const questionItem = harness.events.find( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + assert.equal(questionItem?.type, "turn_item.updated"); + if ( + questionItem?.type === "turn_item.updated" && + questionItem.turnItem.type === "user_input_request" + ) { + assert.deepEqual( + questionItem.turnItem.questions[0]?.options.map((option) => option.label), + ["main", "dev"], + ); + assert.equal(questionItem.turnItem.responseMode, "message"); + } + const questionNode = harness.events.find( + (event) => event.type === "node.updated" && event.node.id === requests[0]?.nodeId, + ); + assert.equal(questionNode?.type === "node.updated" && questionNode.node.countsForRun, false); + const contextReport = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.equal(contextReport?.type, "provider_turn.updated"); + if (contextReport?.type === "provider_turn.updated") { + assert.equal( + contextReport.providerTurn.runAttemptId, + RunAttemptId.make("async-question-attempt"), + ); + assert.equal(contextReport.providerTurn.providerThreadId, harness.providerThread.id); + assert.equal(contextReport.providerTurn.tokenUsage?.usedTokens, 15); + assert.equal(contextReport.providerTurn.tokenUsage?.maxTokens, 200_000); + } + const completed = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.equal(completed?.type, "provider_turn.updated"); + if (completed?.type === "provider_turn.updated") { + assert.deepEqual(completed.providerTurn.turnTokenUsage, { + usageStatus: "complete", + usageScope: "main_agent", + hasSubagents: false, inputTokens: 10, cachedInputTokens: 2, outputTokens: 5, - reasoningOutputTokens: 1, - }; - const transcript = makeCodexReplayTranscript({ - scenario: "async-question-and-billed-usage", - entries: [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "Continue while I decide.", - }), - { - type: "emit_inbound", - label: "question", - frame: { - method: "item/completed", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - item: { - type: "agentMessage", - id: "async-question-item", - text: "Which branch?", - delivery: "async", - questions: [{ title: "Which branch?", options: ["main", "dev"] }], + reasoningTokens: 1, + }); + } + assert.isEmpty(assistantMessages(harness.events)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("returns a Codex question's answer under its native question id", () => + Effect.gen(function* () { + const nativeThreadId = "question-id-thread"; + const nativeTurnId = "question-id-turn"; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-question-native-id", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Pick one." }), + { + type: "emit_inbound", + label: "question", + frame: { + id: 100, + method: "item/tool/requestUserInput", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: "question-id-item", + isBlocking: true, + questions: [ + { + id: " choice ", + header: "Choice", + question: "Which option?", + options: [{ label: "A", description: "Option A" }], }, - }, + ], }, }, - { - type: "emit_inbound", - label: "usage", - frame: { - method: "thread/tokenUsage/updated", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, - }, + }, + { + type: "expect_outbound", + label: "answer", + frame: { id: 100, result: { answers: { " choice ": { answers: ["A"] } } } }, + }, + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("question-id-attempt"), + text: "Pick one.", + }), + ); + const questionItem = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request" + ? [event.turnItem] + : [], + )[0]; + const request = () => + harness.events.flatMap((event) => + event.type === "runtime_request.updated" ? [event.runtimeRequest] : [], + )[0]; + yield* harness.until(() => questionItem() !== undefined && request() !== undefined); + const publishedId = questionItem()!.questions[0]!.id; + yield* harness.runtime.respondToRuntimeRequest({ + requestId: request()!.id, + answers: { [publishedId]: ["A"] }, + }); + yield* harness.firstTerminal; + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("records the model Codex reports on the root provider turn", () => + Effect.gen(function* () { + const nativeThreadId = "reported-model-thread"; + const nativeTurnId = "reported-model-turn"; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-reported-model", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }), + { + type: "emit_inbound", + label: "rerouted", + frame: { + method: "model/rerouted", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + fromModel: "gpt-6-astra", + toModel: "gpt-5.6-sol", + reason: "highRiskCyberActivity", + }, + }, + }, + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("reported-model-attempt"), + text: "say hi", + }), + ); + yield* harness.firstTerminal; + const completed = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.equal(completed?.type, "provider_turn.updated"); + if (completed?.type !== "provider_turn.updated") return; + assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]); + assert.equal(completed.providerTurn.model, "gpt-5.6-sol"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each(["before", "during"] as const)( + "surfaces a user MCP server that fails to start %s the turn", + (timing) => + Effect.gen(function* () { + const nativeThreadId = "mcp-startup-failed-thread"; + const nativeTurnId = "mcp-startup-failed-turn"; + const startupError = + "MCP client for `example_mcp` failed to start: MCP startup failed: handshaking with MCP server failed"; + const startup: Array = [ + { + type: "emit_inbound", + label: "mcp-starting", + frame: { + method: "mcpServer/startupStatus/updated", + params: { + threadId: nativeThreadId, + name: "example_mcp", + status: "starting", + error: null, + failureReason: null, + }, + }, + }, + { + type: "emit_inbound", + label: "mcp-failed", + frame: { + method: "mcpServer/startupStatus/updated", + params: { + threadId: nativeThreadId, + name: "example_mcp", + status: "failed", + error: startupError, + failureReason: null, }, }, + }, + ]; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "use example_mcp", + }); + const turnStart = preamble.findIndex( + (entry) => entry.type === "expect_outbound" && entry.label === "turn/start", + ); + const transcript = makeCodexReplayTranscript({ + scenario: "codex-mcp-startup-failed", + entries: [ + ...(timing === "before" + ? [...preamble.slice(0, turnStart), ...startup, ...preamble.slice(turnStart)] + : [...preamble, ...startup]), { type: "emit_inbound", label: "complete", @@ -2279,70 +2615,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("async-question-attempt"), - text: "Continue while I decide.", + attemptId: RunAttemptId.make("mcp-startup-failed-attempt"), + text: "use example_mcp", }), ); yield* harness.firstTerminal; - const requests = harness.events.flatMap((event) => - event.type === "runtime_request.updated" ? [event.runtimeRequest] : [], - ); - assert.lengthOf(requests, 1); - assert.equal(requests[0]?.status, "pending"); - assert.deepEqual(requests[0]?.responseCapability, { type: "message" }); - const questionItem = harness.events.find( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", - ); - assert.equal(questionItem?.type, "turn_item.updated"); - if ( - questionItem?.type === "turn_item.updated" && - questionItem.turnItem.type === "user_input_request" - ) { - assert.deepEqual( - questionItem.turnItem.questions[0]?.options.map((option) => option.label), - ["main", "dev"], - ); - assert.equal(questionItem.turnItem.responseMode, "message"); - } - const questionNode = harness.events.find( - (event) => event.type === "node.updated" && event.node.id === requests[0]?.nodeId, - ); - assert.equal( - questionNode?.type === "node.updated" && questionNode.node.countsForRun, - false, - ); - const contextReport = harness.events.find( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, - ); - assert.equal(contextReport?.type, "provider_turn.updated"); - if (contextReport?.type === "provider_turn.updated") { - assert.equal( - contextReport.providerTurn.runAttemptId, - RunAttemptId.make("async-question-attempt"), - ); - assert.equal(contextReport.providerTurn.providerThreadId, harness.providerThread.id); - assert.equal(contextReport.providerTurn.tokenUsage?.usedTokens, 15); - assert.equal(contextReport.providerTurn.tokenUsage?.maxTokens, 200_000); - } - const completed = harness.events.find( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "completed", - ); - assert.equal(completed?.type, "provider_turn.updated"); - if (completed?.type === "provider_turn.updated") { - assert.deepEqual(completed.providerTurn.turnTokenUsage, { - usageStatus: "complete", - usageScope: "main_agent", - hasSubagents: false, - inputTokens: 10, - cachedInputTokens: 2, - outputTokens: 5, - reasoningTokens: 1, - }); - } - assert.isEmpty(assistantMessages(harness.events)); + const surfaced = harness.events.filter((event) => { + const serialized = JSON.stringify(event); + return serialized.includes("example_mcp") && serialized.includes("failed to start"); + }); + assert.isNotEmpty(surfaced); }).pipe( Effect.provide( Layer.mergeAll( @@ -2353,614 +2635,582 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ), - ), ); - it.effect("records the model Codex reports on the root provider turn", () => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "reported-model-thread"; - const nativeTurnId = "reported-model-turn"; - const transcript = makeCodexReplayTranscript({ - scenario: "codex-reported-model", - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }), - { - type: "emit_inbound", - label: "rerouted", - frame: { - method: "model/rerouted", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - fromModel: "gpt-6-astra", - toModel: "gpt-5.6-sol", - reason: "highRiskCyberActivity", - }, - }, + it.effect("stops asking for commands the user allowed for the session", () => + Effect.gen(function* () { + const nativeThreadId = "session-approval-thread"; + const turnIds = [ + "session-approval-turn-1", + "session-approval-turn-2", + "session-approval-turn-3", + ]; + const turnPolicies = { + "approval-required": { + approvalPolicy: "untrusted", + approvalsReviewer: "user", + sandboxPolicy: { type: "readOnly" }, + }, + "full-access": { + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + }, + } as const; + const turnModes = ["approval-required", "full-access", "approval-required"] as const; + const turnText = (index: number) => `Review round ${index + 1}.`; + const startTurn = (index: number): ReadonlyArray => [ + { + type: "expect_outbound", + label: `turn ${index + 1} turn/start`, + frame: { + id: 3 + index, + method: "turn/start", + params: { + threadId: nativeThreadId, + input: [{ type: "text", text: turnText(index) }], + cwd: "/workspace", + model: "gpt-5.4", + ...turnPolicies[turnModes[index]!], + summary: "auto", + collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, }, - { - type: "emit_inbound", - label: "complete", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, + }, + }, + { + type: "emit_inbound", + label: `turn ${index + 1} turn/start`, + frame: { + id: 3 + index, + result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) }, + }, + }, + turnEvent("turn/started", turnIds[index]!), + ]; + const approval = (input: { + readonly id: number; + readonly turnId: string; + readonly kind: "commandExecution" | "fileChange"; + readonly itemId: string; + readonly decision: string; + }): ReadonlyArray => [ + { + type: "emit_inbound", + label: `${input.itemId} approval`, + frame: { + id: input.id, + method: `item/${input.kind}/requestApproval`, + params: { + threadId: nativeThreadId, + turnId: input.turnId, + itemId: input.itemId, + startedAtMs: 1782622441000, + ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}), }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("reported-model-attempt"), - text: "say hi", + }, + }, + { + type: "expect_outbound", + label: `${input.itemId} decision`, + frame: { id: input.id, result: { decision: input.decision } }, + }, + ]; + const turnEvent = ( + method: "turn/started" | "turn/completed", + turnId: string, + ): CodexReplay.CodexAppServerReplayEntry => ({ + type: "emit_inbound", + label: `${turnId} ${method}`, + frame: { + method, + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: turnId, + status: method === "turn/started" ? "inProgress" : "completed", + }), + }, + }, + }); + const [patchRequest, patchDecision] = approval({ + id: 102, + turnId: turnIds[0]!, + kind: "fileChange", + itemId: "first-patch", + decision: "acceptForSession", + }); + const transcript = makeCodexReplayTranscript({ + scenario: "codex-session-approvals", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: turnIds[0]!, + prompt: turnText(0), + }).slice(0, -3), + ...startTurn(0), + ...approval({ + id: 100, + turnId: turnIds[0]!, + kind: "commandExecution", + itemId: "first-command", + decision: "acceptForSession", }), - ); - yield* harness.firstTerminal; - const completed = harness.events.find( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "completed", - ); - assert.equal(completed?.type, "provider_turn.updated"); - if (completed?.type !== "provider_turn.updated") return; - assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]); - assert.equal(completed.providerTurn.model, "gpt-5.6-sol"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + patchRequest!, + ...approval({ + id: 101, + turnId: turnIds[0]!, + kind: "commandExecution", + itemId: "second-command", + decision: "acceptForSession", + }), + turnEvent("turn/completed", turnIds[0]!), + ...startTurn(1), + patchDecision!, + turnEvent("turn/completed", turnIds[1]!), + ...startTurn(2), + ...approval({ + id: 103, + turnId: turnIds[2]!, + kind: "commandExecution", + itemId: "third-command", + decision: "accept", + }), + ...approval({ + id: 104, + turnId: turnIds[2]!, + kind: "fileChange", + itemId: "second-patch", + decision: "accept", + }), + turnEvent("turn/completed", turnIds[2]!), + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + const requests = () => [ + ...new Map( + harness.events.flatMap((event) => + event.type === "runtime_request.updated" + ? [[event.runtimeRequest.id, event.runtimeRequest] as const] + : [], ), - ), - ), - ), - ); + ).values(), + ]; + const answer = ( + count: number, + kind: "command" | "file-change", + decision: ProviderApprovalDecision, + ) => + Effect.gen(function* () { + yield* harness.until(() => requests().length === count); + const request = requests()[count - 1]!; + assert.equal(request.kind, kind); + yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision }); + }); - it.effect.each(["before", "during"] as const)( - "surfaces a user MCP server that fails to start %s the turn", - (timing) => - Effect.scoped( + const runTurn = (index: number) => Effect.gen(function* () { - const nativeThreadId = "mcp-startup-failed-thread"; - const nativeTurnId = "mcp-startup-failed-turn"; - const startupError = - "MCP client for `example_mcp` failed to start: MCP startup failed: handshaking with MCP server failed"; - const startup: Array = [ - { - type: "emit_inbound", - label: "mcp-starting", - frame: { - method: "mcpServer/startupStatus/updated", - params: { - threadId: nativeThreadId, - name: "example_mcp", - status: "starting", - error: null, - failureReason: null, - }, - }, - }, - { - type: "emit_inbound", - label: "mcp-failed", - frame: { - method: "mcpServer/startupStatus/updated", - params: { - threadId: nativeThreadId, - name: "example_mcp", - status: "failed", - error: startupError, - failureReason: null, - }, - }, - }, - ]; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "use example_mcp", - }); - const turnStart = preamble.findIndex( - (entry) => entry.type === "expect_outbound" && entry.label === "turn/start", - ); - const transcript = makeCodexReplayTranscript({ - scenario: "codex-mcp-startup-failed", - entries: [ - ...(timing === "before" - ? [...preamble.slice(0, turnStart), ...startup, ...preamble.slice(turnStart)] - : [...preamble, ...startup]), - { - type: "emit_inbound", - label: "complete", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("mcp-startup-failed-attempt"), - text: "use example_mcp", + attemptId: RunAttemptId.make(`session-approvals-${index + 1}`), + text: turnText(index), }), - ); - yield* harness.firstTerminal; - const surfaced = harness.events.filter((event) => { - const serialized = JSON.stringify(event); - return serialized.includes("example_mcp") && serialized.includes("failed to start"); + runOrdinal: index + 1, + providerTurnOrdinal: index + 1, + runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! }, }); - assert.isNotEmpty(surfaced); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), + }); + + yield* runTurn(0); + yield* answer(1, "command", "acceptForSession"); + yield* harness.until(() => requests().length === 2); + yield* harness.awaitTerminal(1); + yield* runTurn(1); + yield* answer(2, "file-change", "acceptForSession"); + yield* harness.awaitTerminal(2); + yield* runTurn(2); + yield* answer(3, "command", "accept"); + yield* answer(4, "file-change", "accept"); + yield* harness.awaitTerminal(3); + assert.lengthOf(requests(), 4); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), + ), ); - it.effect("stops asking for commands the user allowed for the session", () => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "session-approval-thread"; - const turnIds = [ - "session-approval-turn-1", - "session-approval-turn-2", - "session-approval-turn-3", - ]; - const turnPolicies = { - "approval-required": { - approvalPolicy: "untrusted", - approvalsReviewer: "user", - sandboxPolicy: { type: "readOnly" }, - }, - "full-access": { - approvalPolicy: "never", - approvalsReviewer: "user", - sandboxPolicy: { type: "dangerFullAccess" }, - }, - } as const; - const turnModes = ["approval-required", "full-access", "approval-required"] as const; - const turnText = (index: number) => `Review round ${index + 1}.`; - const startTurn = (index: number): ReadonlyArray => [ + it.effect("preserves T3 context on the wire and restores it after compaction", () => + Effect.gen(function* () { + const nativeThreadId = "context-thread"; + const nativeTurnId = "context-turn"; + // An explicit Standard must reach Codex, or Codex falls back to Daybreak. + const modelSelection = { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "cyberAccessProgram", value: "standard" }], + }; + const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId, + codexInput: [{ type: "text", text: "work" }], + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + modelSelection, + hasT3Mcp: true, + cyberAccess: { defaultProgram: "daybreakBlue" }, + }); + assert.include( + params.additionalContext?.t3_code_orchestration_01?.value ?? "", + "delegate_task", + ); + const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }); + const transcript = makeCodexReplayTranscript({ + scenario: "restore-context", + entries: [ + ...entries.slice(0, 5), { type: "expect_outbound", - label: `turn ${index + 1} turn/start`, + label: "context turn", + frame: { id: 3, method: "turn/start", params }, + }, + ...entries.slice(6), + { + type: "emit_inbound", + label: "compacted", frame: { - id: 3 + index, - method: "turn/start", + method: "item/completed", params: { threadId: nativeThreadId, - input: [{ type: "text", text: turnText(index) }], - cwd: "/workspace", - model: "gpt-5.4", - ...turnPolicies[turnModes[index]!], - summary: "auto", - collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, + turnId: nativeTurnId, + item: { type: "contextCompaction", id: "compact-context" }, }, }, }, { type: "emit_inbound", - label: `turn ${index + 1} turn/start`, + label: "done", frame: { - id: 3 + index, - result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) }, + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, }, }, - turnEvent("turn/started", turnIds[index]!), - ]; - const approval = (input: { - readonly id: number; - readonly turnId: string; - readonly kind: "commandExecution" | "fileChange"; - readonly itemId: string; - readonly decision: string; - }): ReadonlyArray => [ { - type: "emit_inbound", - label: `${input.itemId} approval`, + type: "expect_outbound", + label: "restore context", frame: { - id: input.id, - method: `item/${input.kind}/requestApproval`, + id: 4, + method: "thread/inject_items", params: { threadId: nativeThreadId, - turnId: input.turnId, - itemId: input.itemId, - startedAtMs: 1782622441000, - ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}), + items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({ + type: "message", + role: "developer", + content: [{ type: "input_text", text: `<${key}>${entry.value}` }], + })), }, }, }, + { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } }, + ], + }); + // Codex queues items injected mid-turn as pending input and samples again. + const wireOrder: Array = []; + const restoreRequested = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + (method) => + method === "thread/inject_items" + ? Effect.sync(() => wireOrder.push(method)).pipe( + Effect.andThen(Deferred.succeed(restoreRequested, undefined)), + ) + : Effect.void, + undefined, + undefined, + undefined, + undefined, + (method) => + Effect.sync(() => { + if (method === "item/completed" || method === "turn/completed") wireOrder.push(method); + }), + Effect.succeed>([ { - type: "expect_outbound", - label: `${input.itemId} decision`, - frame: { id: input.id, result: { decision: input.decision } }, - }, - ]; - const turnEvent = ( - method: "turn/started" | "turn/completed", - turnId: string, - ): CodexReplay.CodexAppServerReplayEntry => ({ - type: "emit_inbound", - label: `${turnId} ${method}`, - frame: { - method, - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ - id: turnId, - status: method === "turn/started" ? "inProgress" : "completed", - }), + slug: modelSelection.model, + name: modelSelection.model, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + options: [ + { id: "standard", label: "Standard" }, + { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true }, + ], + currentValue: "daybreakBlue", + }, + ], }, }, - }); - const [patchRequest, patchDecision] = approval({ - id: 102, - turnId: turnIds[0]!, - kind: "fileChange", - itemId: "first-patch", - decision: "acceptForSession", - }); - const transcript = makeCodexReplayTranscript({ - scenario: "codex-session-approvals", - entries: [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId: turnIds[0]!, - prompt: turnText(0), - }).slice(0, -3), - ...startTurn(0), - ...approval({ - id: 100, - turnId: turnIds[0]!, - kind: "commandExecution", - itemId: "first-command", - decision: "acceptForSession", - }), - patchRequest!, - ...approval({ - id: 101, - turnId: turnIds[0]!, - kind: "commandExecution", - itemId: "second-command", - decision: "acceptForSession", - }), - turnEvent("turn/completed", turnIds[0]!), - ...startTurn(1), - patchDecision!, - turnEvent("turn/completed", turnIds[1]!), - ...startTurn(2), - ...approval({ - id: 103, - turnId: turnIds[2]!, - kind: "commandExecution", - itemId: "third-command", - decision: "accept", - }), - ...approval({ - id: 104, - turnId: turnIds[2]!, - kind: "fileChange", - itemId: "second-patch", - decision: "accept", - }), - turnEvent("turn/completed", turnIds[2]!), - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const requests = () => [ - ...new Map( - harness.events.flatMap((event) => - event.type === "runtime_request.updated" - ? [[event.runtimeRequest.id, event.runtimeRequest] as const] - : [], - ), - ).values(), - ]; - const answer = ( - count: number, - kind: "command" | "file-change", - decision: ProviderApprovalDecision, - ) => - Effect.gen(function* () { - yield* harness.until(() => requests().length === count); - const request = requests()[count - 1]!; - assert.equal(request.kind, kind); - yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision }); - }); - - const runTurn = (index: number) => - Effect.gen(function* () { - yield* harness.runtime.startTurn({ - ...makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`session-approvals-${index + 1}`), - text: turnText(index), - }), - runOrdinal: index + 1, - providerTurnOrdinal: index + 1, - runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! }, - }); - }); - - yield* runTurn(0); - yield* answer(1, "command", "acceptForSession"); - yield* harness.until(() => requests().length === 2); - yield* harness.awaitTerminal(1); - yield* runTurn(1); - yield* answer(2, "file-change", "acceptForSession"); - yield* harness.awaitTerminal(2); - yield* runTurn(2); - yield* answer(3, "command", "accept"); - yield* answer(4, "file-change", "accept"); - yield* harness.awaitTerminal(3); - assert.lengthOf(requests(), 4); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + ]), + ); + yield* (yield* McpProviderSessions.McpProviderSessions).set({ + environmentId: EnvironmentId.make("test"), + threadId: harness.threadId, + providerSessionId: "context-session", + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer test", + browserToolsAvailable: true, + }); + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("context-attempt"), + text: "work", + }), + modelSelection, + }); + yield* harness.firstTerminal; + yield* Deferred.await(restoreRequested); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.deepEqual( + wireOrder, + ["item/completed", "turn/completed", "thread/inject_items"], + "restored T3 context while the compacting native turn was still running", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("preserves T3 context on the wire and restores it after compaction", () => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "context-thread"; - const nativeTurnId = "context-turn"; - // An explicit Standard must reach Codex, or Codex falls back to Daybreak. - const modelSelection = { - ...CODEX_TEST_MODEL_SELECTION, - options: [{ id: "cyberAccessProgram", value: "standard" }], - }; - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId, - codexInput: [{ type: "text", text: "work" }], - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - modelSelection, - hasT3Mcp: true, - cyberAccess: { defaultProgram: "daybreakBlue" }, - }); - assert.include( - params.additionalContext?.t3_code_orchestration_01?.value ?? "", - "delegate_task", - ); - const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }); - const transcript = makeCodexReplayTranscript({ - scenario: "restore-context", - entries: [ - ...entries.slice(0, 5), - { - type: "expect_outbound", - label: "context turn", - frame: { id: 3, method: "turn/start", params }, - }, - ...entries.slice(6), - { - type: "emit_inbound", - label: "compacted", - frame: { - method: "item/completed", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - item: { type: "contextCompaction", id: "compact-context" }, - }, - }, - }, - { - type: "emit_inbound", - label: "done", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, + it.effect("compacts Codex with the native RPC and completes the compaction turn", () => + Effect.gen(function* () { + const nativeThreadId = "compact-thread"; + const nativeTurnId = "compact-turn"; + const item = { type: "contextCompaction", id: "compact-item" }; + const transcript = makeCodexReplayTranscript({ + scenario: "native-compaction", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "unused" }).slice(0, 5), + { + type: "expect_outbound", + label: "compact", + frame: { + id: 3, + method: "thread/compact/start", + params: { threadId: nativeThreadId }, }, - { - type: "expect_outbound", - label: "restore context", - frame: { - id: 4, - method: "thread/inject_items", - params: { - threadId: nativeThreadId, - items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({ - type: "message", - role: "developer", - content: [{ type: "input_text", text: `<${key}>${entry.value}` }], - })), - }, + }, + { type: "emit_inbound", label: "compact", frame: { id: 3, result: {} } }, + { + type: "emit_inbound", + label: "start", + frame: { + method: "turn/started", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), }, }, - { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } }, - ], - }); - // Codex queues items injected mid-turn as pending input and samples again. - const wireOrder: Array = []; - const restoreRequested = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness( - transcript, - undefined, - (method) => - method === "thread/inject_items" - ? Effect.sync(() => wireOrder.push(method)).pipe( - Effect.andThen(Deferred.succeed(restoreRequested, undefined)), - ) - : Effect.void, - undefined, - undefined, - undefined, - undefined, - (method) => - Effect.sync(() => { - if (method === "item/completed" || method === "turn/completed") - wireOrder.push(method); - }), - Effect.succeed>([ - { - slug: modelSelection.model, - name: modelSelection.model, - isCustom: false, - capabilities: { - optionDescriptors: [ - { - id: "cyberAccessProgram", - label: "Cyber Access", - type: "select", - options: [ - { id: "standard", label: "Standard" }, - { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true }, - ], - currentValue: "daybreakBlue", - }, - ], + }, + ...(["item/started", "item/completed"] as const).map((method) => ({ + type: "emit_inbound" as const, + label: method, + frame: { method, params: { threadId: nativeThreadId, turnId: nativeTurnId, item } }, + })), + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), }, }, - ]), - ); - yield* (yield* McpProviderSessions.McpProviderSessions).set({ - environmentId: EnvironmentId.make("test"), + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + assert.isDefined(harness.runtime.compactThread); + yield* harness.runtime.compactThread!( + makeCodexTestTurnInput({ threadId: harness.threadId, - providerSessionId: "context-session", - providerInstanceId: ProviderInstanceId.make("codex"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer test", - browserToolsAvailable: true, - }); - yield* harness.runtime.startTurn({ - ...makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("context-attempt"), - text: "work", - }), - modelSelection, - }); - yield* harness.firstTerminal; - yield* Deferred.await(restoreRequested); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.deepEqual( - wireOrder, - ["item/completed", "turn/completed", "thread/inject_items"], - "restored T3 context while the compacting native turn was still running", - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("compact-attempt"), + text: "/compact", + }), + ); + yield* harness.firstTerminal; + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + items.map((entry) => entry.status), + ["running", "completed"], + ); + assert.equal(items[0]?.id, items[1]?.id); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); - it.effect("compacts Codex with the native RPC and completes the compaction turn", () => - Effect.scoped( + it.effect.each(["failed", "interrupted", "Stop"] as const)( + "settles unfinished compaction on %s without changing completed compaction", + (outcome) => Effect.gen(function* () { const nativeThreadId = "compact-thread"; const nativeTurnId = "compact-turn"; - const item = { type: "contextCompaction", id: "compact-item" }; + const error = { + message: "Remote compaction stream disconnected", + codexErrorInfo: "other", + additionalDetails: null, + }; const transcript = makeCodexReplayTranscript({ - scenario: "native-compaction", + scenario: `automatic-compaction-${outcome}`, entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "unused" }).slice(0, 5), - { - type: "expect_outbound", - label: "compact", - frame: { - id: 3, - method: "thread/compact/start", - params: { threadId: nativeThreadId }, - }, - }, - { type: "emit_inbound", label: "compact", frame: { id: 3, result: {} } }, - { - type: "emit_inbound", - label: "start", - frame: { - method: "turn/started", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), - }, - }, - }, - ...(["item/started", "item/completed"] as const).map((method) => ({ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + ...( + [ + { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 }, + { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 }, + { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 }, + ] as const + ).map(({ method, id, ...timestamps }) => ({ type: "emit_inbound" as const, - label: method, - frame: { method, params: { threadId: nativeThreadId, turnId: nativeTurnId, item } }, - })), - { - type: "emit_inbound", - label: "complete", + label: `${method}/${id}`, frame: { - method: "turn/completed", + method, params: { threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + turnId: nativeTurnId, + item: { type: "contextCompaction", id }, + ...timestamps, }, }, - }, + })), + ...(outcome === "Stop" + ? [ + { + type: "expect_outbound" as const, + label: "turn/interrupt", + frame: { + id: 4, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId }, + }, + }, + { + type: "emit_inbound" as const, + label: "turn/interrupt/failed", + frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } }, + }, + ] + : [ + { + type: "emit_inbound" as const, + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }), + error: outcome === "failed" ? error : null, + }, + }, + }, + }, + ]), ], }); - const harness = yield* makeCodexReplayHarness(transcript); - assert.isDefined(harness.runtime.compactThread); - yield* harness.runtime.compactThread!( + const compactionStarted = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness(transcript, (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "unfinished-item" && + event.turnItem.status === "running" && + event.turnItem.providerTurnId !== null + ? Deferred.succeed(compactionStarted, event.turnItem.providerTurnId) + : Effect.void, + ); + yield* TestClock.setTime(1782622445000); + yield* harness.runtime.startTurn( makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("compact-attempt"), - text: "/compact", + attemptId: RunAttemptId.make(`compact-${outcome}-attempt`), + text: "Continue.", }), ); + if (outcome === "Stop") { + const providerTurnId = yield* Deferred.await(compactionStarted); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.exit); + assert.equal(interrupt._tag, "Failure"); + } yield* harness.firstTerminal; const items = harness.events.flatMap((event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction" ? [event.turnItem] : [], ); + const completed = items.filter((item) => item.nativeItemRef?.nativeId === "completed-item"); + const unfinished = items.filter( + (item) => item.nativeItemRef?.nativeId === "unfinished-item", + ); + const status = outcome === "failed" ? "failed" : "interrupted"; + assert.deepEqual( + unfinished.map((item) => item.status), + ["running", status], + ); + assert.equal(unfinished[0]?.id, unfinished[1]?.id); + assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000)); assert.deepEqual( - items.map((entry) => entry.status), + unfinished[1]?.completedAt, + DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000), + ); + assert.deepEqual( + completed.map((item) => item.status), ["running", "completed"], ); - assert.equal(items[0]?.id, items[1]?.id); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000)); + assert.deepEqual(completed[1]?.completedAt, DateTime.makeUnsafe(1782622442000)); + assert.equal(harness.terminalEvents()[0]?.status, status); + if (outcome === "failed") { + assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message); + } }).pipe( Effect.provide( Layer.mergeAll( @@ -2971,149 +3221,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ), - ), - ); - - it.effect.each(["failed", "interrupted", "Stop"] as const)( - "settles unfinished compaction on %s without changing completed compaction", - (outcome) => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "compact-thread"; - const nativeTurnId = "compact-turn"; - const error = { - message: "Remote compaction stream disconnected", - codexErrorInfo: "other", - additionalDetails: null, - }; - const transcript = makeCodexReplayTranscript({ - scenario: `automatic-compaction-${outcome}`, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - ...( - [ - { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 }, - { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 }, - { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 }, - ] as const - ).map(({ method, id, ...timestamps }) => ({ - type: "emit_inbound" as const, - label: `${method}/${id}`, - frame: { - method, - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - item: { type: "contextCompaction", id }, - ...timestamps, - }, - }, - })), - ...(outcome === "Stop" - ? [ - { - type: "expect_outbound" as const, - label: "turn/interrupt", - frame: { - id: 4, - method: "turn/interrupt", - params: { threadId: nativeThreadId, turnId: nativeTurnId }, - }, - }, - { - type: "emit_inbound" as const, - label: "turn/interrupt/failed", - frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } }, - }, - ] - : [ - { - type: "emit_inbound" as const, - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }), - error: outcome === "failed" ? error : null, - }, - }, - }, - }, - ]), - ], - }); - const compactionStarted = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness(transcript, (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "unfinished-item" && - event.turnItem.status === "running" && - event.turnItem.providerTurnId !== null - ? Deferred.succeed(compactionStarted, event.turnItem.providerTurnId) - : Effect.void, - ); - yield* TestClock.setTime(1782622445000); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`compact-${outcome}-attempt`), - text: "Continue.", - }), - ); - if (outcome === "Stop") { - const providerTurnId = yield* Deferred.await(compactionStarted); - const interrupt = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.exit); - assert.equal(interrupt._tag, "Failure"); - } - yield* harness.firstTerminal; - const items = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "compaction" - ? [event.turnItem] - : [], - ); - const completed = items.filter( - (item) => item.nativeItemRef?.nativeId === "completed-item", - ); - const unfinished = items.filter( - (item) => item.nativeItemRef?.nativeId === "unfinished-item", - ); - const status = outcome === "failed" ? "failed" : "interrupted"; - assert.deepEqual( - unfinished.map((item) => item.status), - ["running", status], - ); - assert.equal(unfinished[0]?.id, unfinished[1]?.id); - assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000)); - assert.deepEqual( - unfinished[1]?.completedAt, - DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000), - ); - assert.deepEqual( - completed.map((item) => item.status), - ["running", "completed"], - ); - assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000)); - assert.deepEqual(completed[1]?.completedAt, DateTime.makeUnsafe(1782622442000)); - assert.equal(harness.terminalEvents()[0]?.status, status); - if (outcome === "failed") { - assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), ); it.effect.each([ @@ -3232,114 +3339,112 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect("resumes a provider thread without requesting or decoding its history", () => - 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, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }, + 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, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, }, - { - type: "emit_inbound", - label: "thread/resume", - frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - { - type: "expect_outbound", - label: "thread/resume without an app thread", - frame: { - id: 4, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }, + }, + { + type: "emit_inbound", + label: "thread/resume", + frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, + }, + { + type: "expect_outbound", + label: "thread/resume without an app thread", + frame: { + id: 4, + method: "thread/resume", + params: { + threadId: nativeThreadId, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, }, - { - type: "emit_inbound", - label: "thread/resume without an app thread", - frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - { - type: "expect_outbound", - label: "thread/resume with an explicit app thread", - frame: { - id: 5, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }, + }, + { + type: "emit_inbound", + label: "thread/resume without an app thread", + frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, + }, + { + type: "expect_outbound", + label: "thread/resume with an explicit app thread", + frame: { + id: 5, + method: "thread/resume", + params: { + threadId: nativeThreadId, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, }, - { - type: "emit_inbound", - label: "thread/resume with an explicit app thread", - frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - ], - }); - const resumeThreadEnvs: Array = []; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method, params) => - Effect.sync(() => { - if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params)); - }), - ); - const resumed = yield* harness.runtime.resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - yield* harness.runtime.resumeThread({ - providerThread: { ...harness.providerThread, appThreadId: null }, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`); - yield* harness.runtime.resumeThread({ - threadId: explicitThreadId, - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); + }, + { + type: "emit_inbound", + label: "thread/resume with an explicit app thread", + frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, + }, + ], + }); + const resumeThreadEnvs: Array = []; + const harness = yield* makeCodexReplayHarness( + transcript, + () => Effect.void, + (method, params) => + Effect.sync(() => { + if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params)); + }), + ); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + yield* harness.runtime.resumeThread({ + providerThread: { ...harness.providerThread, appThreadId: null }, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`); + yield* harness.runtime.resumeThread({ + threadId: explicitThreadId, + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - assert.equal(resumed.status, "idle"); - assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); - assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal(resumed.status, "idle"); + assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); + assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -3366,113 +3471,111 @@ describe("CodexAdapterV2 post-settle continuation", () => { ] as const ).map(([name, resumeError, failAt, finalError]) => ({ name, resumeError, failAt, finalError })), )("$name", ({ name, resumeError, failAt, finalError }) => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "saved-thread"; - const params = { - threadId: nativeThreadId, - excludeTurns: true, - cwd: CODEX_TEST_RUNTIME_POLICY.cwd, - model: CODEX_TEST_MODEL_SELECTION.model, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }; - const entries: Array = [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "unused-turn", - prompt: "unused-prompt", - }).slice(0, 5), + Effect.gen(function* () { + const nativeThreadId = "saved-thread"; + const params = { + threadId: nativeThreadId, + excludeTurns: true, + cwd: CODEX_TEST_RUNTIME_POLICY.cwd, + model: CODEX_TEST_MODEL_SELECTION.model, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }; + const entries: Array = [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5), + { + type: "expect_outbound", + label: "resume archived thread", + frame: { id: 3, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "resume error", + frame: { id: 3, error: { code: -32600, message: resumeError } }, + }, + ]; + if (failAt !== 3) { + entries.push( { type: "expect_outbound", - label: "resume archived thread", - frame: { id: 3, method: "thread/resume", params }, + label: "unarchive same thread", + frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } }, }, { type: "emit_inbound", - label: "resume error", - frame: { id: 3, error: { code: -32600, message: resumeError } }, + label: "unarchive result", + frame: + failAt === 4 + ? { id: 4, error: { code: -32600, message: finalError } } + : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } }, }, - ]; - if (failAt !== 3) { - entries.push( - { - type: "expect_outbound", - label: "unarchive same thread", - frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } }, - }, - { - type: "emit_inbound", - label: "unarchive result", - frame: - failAt === 4 - ? { id: 4, error: { code: -32600, message: finalError } } - : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } }, - }, - ); - } - if (failAt === 0 || failAt === 5) { - entries.push( - { - type: "expect_outbound", - label: "retry identical resume", - frame: { id: 5, method: "thread/resume", params }, - }, - { - type: "emit_inbound", - label: "retry result", - frame: - failAt === 5 - ? { id: 5, error: { code: -32600, message: finalError } } - : { - id: 5, - result: { - thread: { - id: nativeThreadId, - updatedAt: 1782622450, - turns: [{ type: "unknown-history-item" }], - }, + ); + } + if (failAt === 0 || failAt === 5) { + entries.push( + { + type: "expect_outbound", + label: "retry identical resume", + frame: { id: 5, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "retry result", + frame: + failAt === 5 + ? { id: 5, error: { code: -32600, message: finalError } } + : { + id: 5, + result: { + thread: { + id: nativeThreadId, + updatedAt: 1782622450, + turns: [{ type: "unknown-history-item" }], }, }, - }, - ); - } - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ scenario: name, entries }), - ); - const resume = harness.runtime.resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - if (failAt !== 0) { - const error = yield* Effect.flip(resume); - assert.equal(error._tag, "ProviderAdapterResumeThreadError"); - assert.nestedPropertyVal(error, "cause.errorMessage", finalError); - assert.nestedPropertyVal( - error, - "cause.method", - failAt === 4 ? "thread/unarchive" : "thread/resume", - ); - assert.nestedPropertyVal(error, "cause.requestId", String(failAt)); - return; - } - const resumed = yield* resume; - assert.equal(resumed.id, harness.providerThread.id); - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - assert.deepEqual( - resumed.nativeConversationHeadRef, - harness.providerThread.nativeConversationHeadRef, + }, + }, ); - assert.equal(resumed.status, "idle"); - assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ scenario: name, entries }), + ); + const resume = harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + if (failAt !== 0) { + const error = yield* Effect.flip(resume); + assert.equal(error._tag, "ProviderAdapterResumeThreadError"); + assert.nestedPropertyVal(error, "cause.errorMessage", finalError); + assert.nestedPropertyVal( + error, + "cause.method", + failAt === 4 ? "thread/unarchive" : "thread/resume", + ); + assert.nestedPropertyVal(error, "cause.requestId", String(failAt)); + return; + } + const resumed = yield* resume; + assert.equal(resumed.id, harness.providerThread.id); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.deepEqual( + resumed.nativeConversationHeadRef, + harness.providerThread.nativeConversationHeadRef, + ); + assert.equal(resumed.status, "idle"); + assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -3483,99 +3586,97 @@ describe("CodexAdapterV2 post-settle continuation", () => { { name: "waits for thread/closed after a closing error", closedFirst: false }, { name: "retries at once when the thread already closed", closedFirst: true }, ])("$name", ({ name, closedFirst }) => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "closing-thread"; - const params = { - threadId: nativeThreadId, - excludeTurns: true, - cwd: CODEX_TEST_RUNTIME_POLICY.cwd, - model: CODEX_TEST_MODEL_SELECTION.model, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }; - const closed: CodexReplay.CodexAppServerReplayEntry = { - type: "emit_inbound", - label: "thread closed", - frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, - }; - const closingError: CodexReplay.CodexAppServerReplayEntry = { - type: "emit_inbound", - label: "resume closing error", - frame: { - id: 4, - error: { - code: -32600, - message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`, - }, + Effect.gen(function* () { + const nativeThreadId = "closing-thread"; + const params = { + threadId: nativeThreadId, + excludeTurns: true, + cwd: CODEX_TEST_RUNTIME_POLICY.cwd, + model: CODEX_TEST_MODEL_SELECTION.model, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }; + const closed: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "thread closed", + frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, + }; + const closingError: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "resume closing error", + frame: { + id: 4, + error: { + code: -32600, + message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`, }, - }; - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ - scenario: name, - entries: [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "unused-turn", - prompt: "unused-prompt", - }).slice(0, 5), - { - type: "expect_outbound", - label: "unsubscribe", - frame: { - id: 3, - method: "thread/unsubscribe", - params: { threadId: nativeThreadId }, - }, - }, - { - type: "emit_inbound", - label: "unsubscribe result", - frame: { id: 3, result: { status: "unsubscribed" } }, - }, - { - type: "expect_outbound", - label: "resume closing thread", - frame: { id: 4, method: "thread/resume", params }, - }, - ...(closedFirst ? [closed, closingError] : [closingError, closed]), - { - type: "expect_outbound", - label: "retry identical resume", - frame: { id: 5, method: "thread/resume", params }, + }, + }; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: name, + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5), + { + type: "expect_outbound", + label: "unsubscribe", + frame: { + id: 3, + method: "thread/unsubscribe", + params: { threadId: nativeThreadId }, }, - { - type: "emit_inbound", - label: "retry result", - frame: { - id: 5, - result: { - thread: { - id: nativeThreadId, - updatedAt: 1782622450, - turns: [{ type: "unknown-history-item" }], - }, + }, + { + type: "emit_inbound", + label: "unsubscribe result", + frame: { id: 3, result: { status: "unsubscribed" } }, + }, + { + type: "expect_outbound", + label: "resume closing thread", + frame: { id: 4, method: "thread/resume", params }, + }, + ...(closedFirst ? [closed, closingError] : [closingError, closed]), + { + type: "expect_outbound", + label: "retry identical resume", + frame: { id: 5, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "retry result", + frame: { + id: 5, + result: { + thread: { + id: nativeThreadId, + updatedAt: 1782622450, + turns: [{ type: "unknown-history-item" }], }, }, }, - ], - }), - ); - yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); - const resumed = yield* harness.runtime.resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - assert.equal(resumed.status, "idle"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + }, + ], + }), + ); + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal(resumed.status, "idle"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -3594,750 +3695,900 @@ describe("CodexAdapterV2 post-settle continuation", () => { "steer", "start-fails", ] as const)("handles terminal Codex capacity failures when retries %s", (outcome) => - Effect.scoped( - Effect.gen(function* () { - const scenario = `capacity-${outcome}`; - const nativeThreadId = `native-${scenario}`; - const nativeTurnId = (attempt: number) => `${nativeThreadId}-${attempt}`; - const prompt = "Continue the task."; - const capacityError = { - message: "Selected model is at capacity. Please try a different model.", - codexErrorInfo: "serverOverloaded", - }; - const failureEntries = (attempt: number): Array => [ - { - type: "emit_inbound", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId(attempt), - willRetry: false, - error: capacityError, - }, + Effect.gen(function* () { + const scenario = `capacity-${outcome}`; + const nativeThreadId = `native-${scenario}`; + const nativeTurnId = (attempt: number) => `${nativeThreadId}-${attempt}`; + const prompt = "Continue the task."; + const capacityError = { + message: "Selected model is at capacity. Please try a different model.", + codexErrorInfo: "serverOverloaded", + }; + const failureEntries = (attempt: number): Array => [ + { + type: "emit_inbound", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId(attempt), + willRetry: false, + error: capacityError, }, }, - { - type: "emit_inbound", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "failed" }), - error: capacityError, - }, + }, + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "failed" }), + error: capacityError, }, }, }, - ]; - const entries = codexReplayPreamble({ + }, + ]; + const entries = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: nativeTurnId(0), + prompt, + }); + entries.push( + ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)), + ); + if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1)); + const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1; + const steeredText = "Use the smaller change."; + for (let attempt = 1; attempt <= retries; attempt++) { + const start = codexReplayPreamble({ nativeThreadId, - nativeTurnId: nativeTurnId(0), + nativeTurnId: nativeTurnId(attempt), prompt, - }); - entries.push( - ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)), - ); - if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1)); - const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1; - const steeredText = "Use the smaller change."; - for (let attempt = 1; attempt <= retries; attempt++) { - const start = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: nativeTurnId(attempt), - prompt, - }).slice(-3); - if ( - outcome === "started-first" || - outcome === "stop-starting" || - outcome === "completed-first" || - outcome === "new-run" - ) { - start.splice(1, 0, ...start.splice(2, 1)); - } - for (const entry of start) { - if (entry.type === "expect_outbound") { + }).slice(-3); + if ( + outcome === "started-first" || + outcome === "stop-starting" || + outcome === "completed-first" || + outcome === "new-run" + ) { + start.splice(1, 0, ...start.splice(2, 1)); + } + for (const entry of start) { + if (entry.type === "expect_outbound") { + entries.push({ + ...entry, + frame: { + id: 3 + attempt, + method: "turn/start", + params: { + threadId: nativeThreadId, + input: [], + cwd: "/workspace", + model: "gpt-5.4", + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + summary: "auto", + collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, + }, + }, + }); + } else if (entry.type === "emit_inbound" && entry.label === "turn/start") { + if (outcome === "completed-first" || outcome === "new-run") entries.push({ - ...entry, + type: "emit_inbound", frame: { - id: 3 + attempt, - method: "turn/start", + method: "turn/completed", params: { threadId: nativeThreadId, - input: [], - cwd: "/workspace", - model: "gpt-5.4", - approvalPolicy: "never", - approvalsReviewer: "user", - sandboxPolicy: { type: "dangerFullAccess" }, - summary: "auto", - collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, + turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "completed" }), }, }, }); - } else if (entry.type === "emit_inbound" && entry.label === "turn/start") { - if (outcome === "completed-first" || outcome === "new-run") - entries.push({ - type: "emit_inbound", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "completed" }), - }, - }, - }); - if (outcome === "new-run") { - entries.push( - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId: nativeTurnId(2), - prompt: "Next task.", - }) - .slice(-3) - .map((next, index) => (index < 2 ? withReplayRequestId(next, 5) : next)), - ...failureEntries(2), - ); - } - entries.push( - outcome === "start-fails" - ? { - type: "emit_inbound", - frame: { - id: 3 + attempt, - error: { code: -32603, message: "Start failed" }, - }, - } - : withReplayRequestId(entry, 3 + attempt), - ); - } else if (outcome !== "start-fails") { + if (outcome === "new-run") { entries.push( - outcome === "stop-starting" && entry.type === "emit_inbound" - ? { ...entry, afterMs: 1_000 } - : entry, + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: nativeTurnId(2), + prompt: "Next task.", + }) + .slice(-3) + .map((next, index) => (index < 2 ? withReplayRequestId(next, 5) : next)), + ...failureEntries(2), ); - if (outcome === "stop-starting") { - entries.push( - { - type: "expect_outbound", + } + entries.push( + outcome === "start-fails" + ? { + type: "emit_inbound", frame: { - id: 5, - method: "turn/interrupt", - params: { threadId: nativeThreadId, turnId: nativeTurnId(attempt) }, + id: 3 + attempt, + error: { code: -32603, message: "Start failed" }, }, + } + : withReplayRequestId(entry, 3 + attempt), + ); + } else if (outcome !== "start-fails") { + entries.push( + outcome === "stop-starting" && entry.type === "emit_inbound" + ? { ...entry, afterMs: 1_000 } + : entry, + ); + if (outcome === "stop-starting") { + entries.push( + { + type: "expect_outbound", + frame: { + id: 5, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId(attempt) }, }, - { type: "emit_inbound", frame: { id: 5, result: {} } }, - ); - } + }, + { type: "emit_inbound", frame: { id: 5, result: {} } }, + ); } } - if (outcome === "exhaust") entries.push(...failureEntries(attempt)); - if ( - outcome === "recover" || - outcome === "completion-only" || - outcome === "started-first" || - outcome === "stop-starting" - ) { - entries.push({ - type: "emit_inbound", + } + if (outcome === "exhaust") entries.push(...failureEntries(attempt)); + if ( + outcome === "recover" || + outcome === "completion-only" || + outcome === "started-first" || + outcome === "stop-starting" + ) { + entries.push({ + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: nativeTurnId(attempt), + status: outcome === "stop-starting" ? "interrupted" : "completed", + }), + }, + }, + }); + } + if (outcome === "stop-continued" || outcome === "steer") { + const steering = outcome === "steer"; + entries.push( + { + type: "expect_outbound", + frame: { + id: 5, + method: steering ? "turn/steer" : "turn/interrupt", + params: steering + ? { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId(attempt), + input: [{ type: "text", text: steeredText }], + } + : { threadId: nativeThreadId, turnId: nativeTurnId(attempt) }, + }, + }, + { + type: "emit_inbound", + frame: { id: 5, result: steering ? { turnId: nativeTurnId(attempt) } : {} }, + }, + { + type: "emit_inbound", frame: { method: "turn/completed", params: { threadId: nativeThreadId, turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), - status: outcome === "stop-starting" ? "interrupted" : "completed", + status: steering ? "completed" : "interrupted", }), }, }, - }); - } - if (outcome === "stop-continued" || outcome === "steer") { - const steering = outcome === "steer"; - entries.push( - { - type: "expect_outbound", - frame: { - id: 5, - method: steering ? "turn/steer" : "turn/interrupt", - params: steering - ? { - threadId: nativeThreadId, - expectedTurnId: nativeTurnId(attempt), - input: [{ type: "text", text: steeredText }], - } - : { threadId: nativeThreadId, turnId: nativeTurnId(attempt) }, - }, - }, - { - type: "emit_inbound", - frame: { id: 5, result: steering ? { turnId: nativeTurnId(attempt) } : {} }, - }, - { - type: "emit_inbound", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ - id: nativeTurnId(attempt), - status: steering ? "completed" : "interrupted", - }), - }, - }, - }, - ); - } + }, + ); } - const milestones = yield* Queue.unbounded(); - const starts: Array = []; - const retryStarted = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ scenario, entries }), - (event) => - event.type === "turn.terminal" || - (event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.status === "running") - ? Queue.offer(milestones, event) - : Effect.void, - (method, params) => - Effect.gen(function* () { - if (method === "turn/start") { - starts.push(params); - if (starts.length === 2) yield* Deferred.succeed(retryStarted, undefined); - } - }), - ); - const turnInput = makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(scenario), - text: prompt, + } + const milestones = yield* Queue.unbounded(); + const starts: Array = []; + const retryStarted = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ scenario, entries }), + (event) => + event.type === "turn.terminal" || + (event.type === "turn_item.updated" && + event.turnItem.type === "error" && + event.turnItem.status === "running") + ? Queue.offer(milestones, event) + : Effect.void, + (method, params) => + Effect.gen(function* () { + if (method === "turn/start") { + starts.push(params); + if (starts.length === 2) yield* Deferred.succeed(retryStarted, undefined); + } + }), + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(scenario), + text: prompt, + }); + yield* harness.runtime.startTurn(turnInput); + for (let attempt = 1; attempt <= Math.max(retries, 1); attempt++) { + const milestone = yield* Queue.take(milestones); + assert.equal(milestone.type, "turn_item.updated"); + if (milestone.type !== "turn_item.updated" || milestone.turnItem.type !== "error") return; + const providerTurnId = milestone.turnItem.providerTurnId; + assert.isNotNull(providerTurnId); + if (providerTurnId === null) return; + assert.deepEqual(milestone.turnItem.retry, { + attempt, + maxAttempts: 5, + retryDelayMs: Math.min(2_000 * 2 ** (attempt - 1), 30_000), }); - yield* harness.runtime.startTurn(turnInput); - for (let attempt = 1; attempt <= Math.max(retries, 1); attempt++) { - const milestone = yield* Queue.take(milestones); - assert.equal(milestone.type, "turn_item.updated"); - if (milestone.type !== "turn_item.updated" || milestone.turnItem.type !== "error") return; - const providerTurnId = milestone.turnItem.providerTurnId; - assert.isNotNull(providerTurnId); - if (providerTurnId === null) return; - assert.deepEqual(milestone.turnItem.retry, { - attempt, - maxAttempts: 5, - retryDelayMs: Math.min(2_000 * 2 ** (attempt - 1), 30_000), + assert.isEmpty(harness.terminalEvents()); + if (outcome === "stop") { + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, }); - assert.isEmpty(harness.terminalEvents()); - if (outcome === "stop") { - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }); - } - const steering = - outcome === "steer" - ? yield* harness.runtime - .steerTurn({ - ...turnInput, - providerTurnId, - message: { ...turnInput.message, text: steeredText }, - }) - .pipe(Effect.forkScoped) - : undefined; - yield* TestClock.adjust(Math.min(2_000 * 2 ** (attempt - 1), 30_000)); - if (outcome === "stop-starting") { - yield* Deferred.await(retryStarted); - const stopping = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("1 second"); - yield* Fiber.join(stopping); - } - if (steering !== undefined) yield* Fiber.join(steering); - if (outcome === "stop-continued") { - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId(1), - ), - ); - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }); - } } - yield* harness.awaitTerminal(1); - if (outcome === "new-run") { - assert.equal((yield* Queue.take(milestones)).type, "turn.terminal"); - yield* harness.runtime.startTurn({ - ...turnInput, - attemptId: RunAttemptId.make("capacity-next-task"), - message: { ...turnInput.message, text: "Next task." }, + const steering = + outcome === "steer" + ? yield* harness.runtime + .steerTurn({ + ...turnInput, + providerTurnId, + message: { ...turnInput.message, text: steeredText }, + }) + .pipe(Effect.forkScoped) + : undefined; + yield* TestClock.adjust(Math.min(2_000 * 2 ** (attempt - 1), 30_000)); + if (outcome === "stop-starting") { + yield* Deferred.await(retryStarted); + const stopping = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(stopping); + } + if (steering !== undefined) yield* Fiber.join(steering); + if (outcome === "stop-continued") { + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId(1), + ), + ); + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, }); - const nextRetry = yield* Queue.take(milestones); - assert.equal(nextRetry.type, "turn_item.updated"); - if (nextRetry.type !== "turn_item.updated" || nextRetry.turnItem.type !== "error") return; - assert.equal(nextRetry.turnItem.retry?.attempt, 1); - return; } - const terminal = harness.terminalEvents()[0]; - assert.equal( - terminal?.status, - outcome === "recover" || - outcome === "completion-only" || - outcome === "steer" || - outcome === "started-first" || - outcome === "completed-first" - ? "completed" - : outcome === "stop" || outcome === "stop-continued" || outcome === "stop-starting" - ? "interrupted" - : "failed", - ); - assert.lengthOf(starts, 1 + retries); - assert.lengthOf(harness.terminalEvents(), 1); - assert.lengthOf( - harness.events.filter( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "running", - ), - outcome === "start-fails" ? 1 : 1 + retries, - ); - const retryItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "error" - ? [event.turnItem] - : [], - ); - assert.isTrue( - ["completed", "failed", "interrupted"].includes(retryItems.at(-1)?.status ?? ""), - ); - assert.lengthOf(new Set(retryItems.map((item) => item.id)), 1); + } + yield* harness.awaitTerminal(1); + if (outcome === "new-run") { + assert.equal((yield* Queue.take(milestones)).type, "turn.terminal"); + yield* harness.runtime.startTurn({ + ...turnInput, + attemptId: RunAttemptId.make("capacity-next-task"), + message: { ...turnInput.message, text: "Next task." }, + }); + const nextRetry = yield* Queue.take(milestones); + assert.equal(nextRetry.type, "turn_item.updated"); + if (nextRetry.type !== "turn_item.updated" || nextRetry.turnItem.type !== "error") return; + assert.equal(nextRetry.turnItem.retry?.attempt, 1); + return; + } + const terminal = harness.terminalEvents()[0]; + assert.equal( + terminal?.status, + outcome === "recover" || + outcome === "completion-only" || + outcome === "steer" || + outcome === "started-first" || + outcome === "completed-first" + ? "completed" + : outcome === "stop" || outcome === "stop-continued" || outcome === "stop-starting" + ? "interrupted" + : "failed", + ); + assert.lengthOf(starts, 1 + retries); + assert.lengthOf(harness.terminalEvents(), 1); + assert.lengthOf( + harness.events.filter( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + outcome === "start-fails" ? 1 : 1 + retries, + ); + const retryItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? [event.turnItem] + : [], + ); + assert.isTrue( + ["completed", "failed", "interrupted"].includes(retryItems.at(-1)?.status ?? ""), + ); + assert.lengthOf(new Set(retryItems.map((item) => item.id)), 1); - if (outcome === "recover") { - const fs = yield* FileSystem.FileSystem; - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-capacity-retry-" }); - const localTranscript = yield* decodeReplayTranscriptJson( - (yield* encodeReplayTranscriptJson( - makeCodexReplayTranscript({ scenario, entries }), - )).replaceAll(yield* encodeStringJson("/workspace"), yield* encodeStringJson(cwd)), + if (outcome === "recover") { + const fs = yield* FileSystem.FileSystem; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-capacity-retry-" }); + const localTranscript = yield* decodeReplayTranscriptJson( + (yield* encodeReplayTranscriptJson( + makeCodexReplayTranscript({ scenario, entries }), + )).replaceAll(yield* encodeStringJson("/workspace"), yield* encodeStringJson(cwd)), + ); + const driver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:capacity-retry"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-capacity-retry"), + threadId, + projectId: ProjectId.make("project:capacity-retry"), + title: "Capacity retry", + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const retrying = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "turn-item.updated" && + event.payload.type === "error" && + event.payload.retry != null && + event.payload.status === "running", + ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), ); - const driver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = ThreadId.make("thread:capacity-retry"); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create-capacity-retry"), - threadId, - projectId: ProjectId.make("project:capacity-retry"), - title: "Capacity retry", - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - const retrying = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "turn-item.updated" && - event.payload.type === "error" && - event.payload.retry != null && - event.payload.status === "running", - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("start-capacity-retry"), - threadId, - messageId: MessageId.make("message:capacity-retry"), - text: prompt, - attachments: [], - createdBy: "user", - creationSource: "web", - dispatchMode: { type: "start_immediately" }, - }); - yield* worker.drain(); - yield* Fiber.join(retrying); - assert.equal( - (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status, - "running", - ); - const completed = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* TestClock.adjust("2 seconds"); - yield* Fiber.join(completed); - yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.equal(projection.runs.at(-1)?.status, "completed"); - assert.deepEqual( - projection.providerTurns.map((turn) => turn.status), - ["failed", "completed"], - ); - assert.lengthOf( - projection.messages.filter((message) => message.role === "user"), - 1, - ); - assert.isNull((yield* Ref.get(driver.state)).failure); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { name: "codex-capacity-retry", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ transcript: localTranscript, driver }), - { runEffectWorker: false }, - ), + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-capacity-retry"), + threadId, + messageId: MessageId.make("message:capacity-retry"), + text: prompt, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* Fiber.join(retrying); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status, + "running", + ); + const completed = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "run.updated" && event.payload.status === "waiting", ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), ); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + yield* TestClock.adjust("2 seconds"); + yield* Fiber.join(completed); + yield* worker.drain(); + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs.at(-1)?.status, "completed"); + assert.deepEqual( + projection.providerTurns.map((turn) => turn.status), + ["failed", "completed"], + ); + assert.lengthOf( + projection.messages.filter((message) => message.role === "user"), + 1, + ); + assert.isNull((yield* Ref.get(driver.state)).failure); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "codex-capacity-retry", runtimePolicyOverride: { cwd } }, + CodexAdapterV2Testkit.layer({ transcript: localTranscript, driver }), + { runEffectWorker: false }, + ), ), + ); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect.each(["exhaust", "recover"] as const)("bounds active-writer retries: %s", (outcome) => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = "thread-open-elsewhere"; - const resumed = yield* Queue.unbounded(); - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "unused-turn", - prompt: "unused-prompt", - }); - const started = preamble[4]; - assert(started?.type === "emit_inbound"); - const entries: Array = preamble.slice(0, 5); - for (let attempt = 0; attempt < (outcome === "recover" ? 2 : 4); attempt++) { - const requestId = 3 + attempt; - entries.push( - { - type: "expect_outbound", - label: "thread/resume", - frame: { - id: requestId, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - cwd: CODEX_TEST_RUNTIME_POLICY.cwd, - model: CODEX_TEST_MODEL_SELECTION.model, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }, + Effect.gen(function* () { + const nativeThreadId = "thread-open-elsewhere"; + const resumed = yield* Queue.unbounded(); + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }); + const started = preamble[4]; + assert(started?.type === "emit_inbound"); + const entries: Array = preamble.slice(0, 5); + for (let attempt = 0; attempt < (outcome === "recover" ? 2 : 4); attempt++) { + const requestId = 3 + attempt; + entries.push( + { + type: "expect_outbound", + label: "thread/resume", + frame: { + id: requestId, + method: "thread/resume", + params: { + threadId: nativeThreadId, + excludeTurns: true, + cwd: CODEX_TEST_RUNTIME_POLICY.cwd, + model: CODEX_TEST_MODEL_SELECTION.model, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, }, }, - outcome === "recover" && attempt === 1 - ? withReplayRequestId(started, requestId) - : { - type: "emit_inbound", - label: "resume result", - frame: { - id: requestId, - error: { - code: -32600, - message: `thread ${nativeThreadId} already has an active writer`, - }, + }, + outcome === "recover" && attempt === 1 + ? withReplayRequestId(started, requestId) + : { + type: "emit_inbound", + label: "resume result", + frame: { + id: requestId, + error: { + code: -32600, + message: `thread ${nativeThreadId} already has an active writer`, }, }, - ); - } - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ - scenario: "codex-resume-active-writer", - entries, - }), - () => Effect.void, - (method) => - method === "thread/resume" - ? Queue.offer(resumed, undefined).pipe(Effect.asVoid) - : Effect.void, + }, ); + } + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-resume-active-writer", + entries, + }), + () => Effect.void, + (method) => + method === "thread/resume" + ? Queue.offer(resumed, undefined).pipe(Effect.asVoid) + : Effect.void, + ); - const resume = yield* harness.runtime - .resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }) - .pipe(Effect.result, Effect.forkChild); + const resume = yield* harness.runtime + .resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }) + .pipe(Effect.result, Effect.forkChild); + yield* Queue.take(resumed); + yield* TestClock.adjust("250 millis"); + yield* Queue.take(resumed); + if (outcome === "exhaust") { + yield* TestClock.adjust("500 millis"); yield* Queue.take(resumed); - yield* TestClock.adjust("250 millis"); + yield* TestClock.adjust("1 second"); yield* Queue.take(resumed); - if (outcome === "exhaust") { - yield* TestClock.adjust("500 millis"); - yield* Queue.take(resumed); - yield* TestClock.adjust("1 second"); - yield* Queue.take(resumed); - } - const result = yield* Fiber.join(resume); - if (outcome === "recover") { - assert.equal(result._tag, "Success"); - return; - } - assert.equal(result._tag, "Failure"); - if (result._tag !== "Failure") return; - const error = result.failure; - - assert.equal(error._tag, "ProviderAdapterThreadInUseError"); - assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id); - assert.include(error.message, "open in another Codex client"); - assert.nestedPropertyVal( - error, - "cause.errorMessage", - `thread ${nativeThreadId} already has an active writer`, - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + const result = yield* Fiber.join(resume); + if (outcome === "recover") { + assert.equal(result._tag, "Success"); + return; + } + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + const error = result.failure; + + assert.equal(error._tag, "ProviderAdapterThreadInUseError"); + assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id); + assert.include(error.message, "open in another Codex client"); + assert.nestedPropertyVal( + error, + "cause.errorMessage", + `thread ${nativeThreadId} already has an active writer`, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect("resolves retryable app-server errors on resumed provider activity", () => - Effect.scoped( - Effect.gen(function* () { - const scenario = "codex-provider-api-retry"; - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "Open github.com.", - }), - { - type: "emit_inbound", - label: "error/retry", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: true, - error: { - message: "Reconnecting... 2/5", - additionalDetails: "The response stream disconnected.", - codexErrorInfo: { - responseStreamDisconnected: { httpStatusCode: 529 }, - }, + Effect.gen(function* () { + const scenario = "codex-provider-api-retry"; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "Open github.com.", + }), + { + type: "emit_inbound", + label: "error/retry", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 2/5", + additionalDetails: "The response stream disconnected.", + codexErrorInfo: { + responseStreamDisconnected: { httpStatusCode: 529 }, }, }, }, }, - { - type: "emit_inbound", - label: "error/retry/waiting-for-network", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: true, - error: { - message: "Reconnecting... waiting for network", - additionalDetails: "Connection failed: error sending request", - codexErrorInfo: { - responseStreamDisconnected: { httpStatusCode: null }, - }, + }, + { + type: "emit_inbound", + label: "error/retry/waiting-for-network", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... waiting for network", + additionalDetails: "Connection failed: error sending request", + codexErrorInfo: { + responseStreamDisconnected: { httpStatusCode: null }, }, }, }, }, - { - type: "emit_inbound", - label: "item/started/after-retry", - frame: { - method: "item/started", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - startedAtMs: 1782622445000, - item: { - type: "commandExecution", - id: "command-after-provider-retry", - command: "pwd", - cwd: "/workspace", - processId: "42", - source: "unifiedExecStartup", - status: "inProgress", - commandActions: [{ type: "unknown", command: "pwd" }], - aggregatedOutput: null, - exitCode: null, - durationMs: null, - }, + }, + { + type: "emit_inbound", + label: "item/started/after-retry", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622445000, + item: { + type: "commandExecution", + id: "command-after-provider-retry", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status: "inProgress", + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: null, + exitCode: null, + durationMs: null, }, }, }, - { - type: "emit_inbound", - label: "item/completed/after-retry", - frame: { - method: "item/completed", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - completedAtMs: 1782622445010, - item: { - type: "commandExecution", - id: "command-after-provider-retry", - command: "pwd", - cwd: "/workspace", - processId: "42", - source: "unifiedExecStartup", - status: "completed", - commandActions: [{ type: "unknown", command: "pwd" }], - aggregatedOutput: "/workspace\n", - exitCode: 0, - durationMs: 10, - }, + }, + { + type: "emit_inbound", + label: "item/completed/after-retry", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + completedAtMs: 1782622445010, + item: { + type: "commandExecution", + id: "command-after-provider-retry", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status: "completed", + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: "/workspace\n", + exitCode: 0, + durationMs: 10, }, }, }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, + }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), }, }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"), - text: "Open github.com.", - }), - ); - yield* harness.awaitTerminal(1); + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"), + text: "Open github.com.", + }), + ); + yield* harness.awaitTerminal(1); + + const retryItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "error" && + event.turnItem.retry !== undefined + ? [event.turnItem] + : [], + ); + assert.lengthOf(retryItems, 3); + assert.equal(retryItems[0]?.status, "running"); + assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected"); + assert.deepEqual(retryItems[0]?.retry, { + attempt: 2, + maxAttempts: 5, + retryDelayMs: null, + }); + assert.deepEqual(retryItems[1]?.retry, { + attempt: 3, + maxAttempts: null, + retryDelayMs: null, + }); + assert.equal(retryItems[2]?.id, retryItems[0]?.id); + assert.equal(retryItems[2]?.status, "completed"); + assert.equal(retryItems[2]?.title, "Provider recovered"); - const retryItems = harness.events.flatMap((event) => + const recoveredIndex = harness.events.findIndex( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "error" && - event.turnItem.retry !== undefined - ? [event.turnItem] - : [], - ); - assert.lengthOf(retryItems, 3); - assert.equal(retryItems[0]?.status, "running"); - assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected"); - assert.deepEqual(retryItems[0]?.retry, { - attempt: 2, - maxAttempts: 5, - retryDelayMs: null, - }); - assert.deepEqual(retryItems[1]?.retry, { - attempt: 3, - maxAttempts: null, - retryDelayMs: null, - }); - assert.equal(retryItems[2]?.id, retryItems[0]?.id); - assert.equal(retryItems[2]?.status, "completed"); - assert.equal(retryItems[2]?.title, "Provider recovered"); - - const recoveredIndex = harness.events.findIndex( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.status === "completed", - ); - const resumedCommandIndex = harness.events.findIndex( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.input === "pwd", - ); - const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); - assert.isAtLeast(recoveredIndex, 0); - assert.isAbove(resumedCommandIndex, recoveredIndex); - assert.isAbove(terminalIndex, resumedCommandIndex); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + event.turnItem.status === "completed", + ); + const resumedCommandIndex = harness.events.findIndex( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.input === "pwd", + ); + const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); + assert.isAtLeast(recoveredIndex, 0); + assert.isAbove(resumedCommandIndex, recoveredIndex); + assert.isAbove(terminalIndex, resumedCommandIndex); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), ); it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () => - Effect.scoped( + Effect.gen(function* () { + const scenario = "codex-provider-retry-stall"; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + { + type: "emit_inbound", + label: "error/retry", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 1/5", + additionalDetails: "exceeded retry limit, last status: 429 Too Many Requests", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 429 } }, + }, + }, + }, + }, + { + type: "expect_outbound", + label: "turn/interrupt", + frame: { + id: 4, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId }, + }, + }, + { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }), + }, + }, + }, + ], + }); + const retryShown = yield* Deferred.make(); + const interruptSent = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + transcript, + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? Deferred.succeed(retryShown, undefined) + : Effect.void, + (method) => + method === "turn/interrupt" ? Deferred.succeed(interruptSent, undefined) : Effect.void, + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-${scenario}`), + }), + ); + yield* Deferred.await(retryShown); + yield* TestClock.adjust("9 minutes"); + assert.isEmpty(harness.terminalEvents()); + yield* TestClock.adjust("1 minute"); + yield* harness.firstTerminal; + yield* Deferred.await(interruptSent); + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal(terminal.failure.code, "responseStreamDisconnected"); + assert.equal( + terminal.failure.message, + "exceeded retry limit, last status: 429 Too Many Requests", + ); + assert.equal(terminal.retry?.attempt, 1); + assert.equal(terminal.threadDisposition, "reusable"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect.each(["completed", "interrupted"] as const)( + "retains Codex reasoning parts when the turn is %s", + (terminalStatus) => Effect.gen(function* () { - const scenario = "codex-provider-retry-stall"; + const scenario = `codex-reasoning-${terminalStatus}`; const nativeThreadId = `native-${scenario}-thread`; const nativeTurnId = `native-${scenario}-turn`; + const prompt = "Explain the check."; const transcript = makeCodexReplayTranscript({ scenario, entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - { - type: "emit_inbound", - label: "error/retry", - frame: { - method: "error", + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), + ...[ + { + method: "item/reasoning/summaryTextDelta", + params: { itemId: "thought", summaryIndex: 0, delta: "Summary " }, + }, + { + method: "item/reasoning/summaryTextDelta", + params: { itemId: "thought", summaryIndex: 0, delta: "one" }, + }, + { + method: "item/reasoning/summaryTextDelta", + params: { itemId: "thought", summaryIndex: 1, delta: "Summary two" }, + }, + { + method: "item/reasoning/textDelta", + params: { itemId: "thought", contentIndex: 0, delta: "Raw trace" }, + }, + { + method: "item/completed", params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: true, - error: { - message: "Reconnecting... 1/5", - additionalDetails: "exceeded retry limit, last status: 429 Too Many Requests", - codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 429 } }, + item: { + type: "commandExecution", + id: "after-thought", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status: "completed", + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: "/workspace", + exitCode: 0, + durationMs: 1, }, }, }, - }, - { - type: "expect_outbound", - label: "turn/interrupt", + ...(terminalStatus === "completed" + ? [ + { + method: "item/completed", + params: { + item: { + type: "reasoning", + id: "thought", + summary: ["Final summary one", "Summary two"], + content: ["Raw trace"], + }, + }, + }, + { + method: "item/completed", + params: { + item: { + type: "reasoning", + id: "completion-only", + summary: ["Completion without deltas"], + content: [], + }, + }, + }, + { + method: "item/reasoning/textDelta", + params: { + itemId: "delta-only", + contentIndex: 0, + delta: "Retained when completion omits content", + }, + }, + { + method: "item/completed", + params: { + item: { type: "reasoning", id: "delta-only", summary: [], content: [] }, + }, + }, + ] + : []), + ].map((event, index) => ({ + type: "emit_inbound" as const, + label: `reasoning-${index}`, frame: { - id: 4, - method: "turn/interrupt", - params: { threadId: nativeThreadId, turnId: nativeTurnId }, + method: event.method, + params: { threadId: nativeThreadId, turnId: nativeTurnId, ...event.params }, }, - }, - { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } }, + })), { type: "emit_inbound", label: "turn/completed", @@ -4345,49 +4596,61 @@ describe("CodexAdapterV2 post-settle continuation", () => { method: "turn/completed", params: { threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }), + turn: makeCodexReplayTurn({ id: nativeTurnId, status: terminalStatus }), }, }, }, ], }); - const retryShown = yield* Deferred.make(); - const interruptSent = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness( - transcript, - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "error" - ? Deferred.succeed(retryShown, undefined) - : Effect.void, - (method) => - method === "turn/interrupt" ? Deferred.succeed(interruptSent, undefined) : Effect.void, - ); + const harness = yield* makeCodexReplayHarness(transcript); yield* harness.runtime.startTurn( makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - text: "Continue.", attemptId: RunAttemptId.make(`attempt-${scenario}`), + text: prompt, }), ); - yield* Deferred.await(retryShown); - yield* TestClock.adjust("9 minutes"); - assert.isEmpty(harness.terminalEvents()); - yield* TestClock.adjust("1 minute"); yield* harness.firstTerminal; - yield* Deferred.await(interruptSent); - const terminal = harness.terminalEvents()[0]; - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.equal(terminal.failure.class, "usage_limit"); - assert.equal(terminal.failure.code, "responseStreamDisconnected"); - assert.equal( - terminal.failure.message, - "exceeded retry limit, last status: 429 Too Many Requests", + const latest = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "reasoning" + ? [[event.turnItem.id, event.turnItem] as const] + : [], + ), ); - assert.equal(terminal.retry?.attempt, 1); - assert.equal(terminal.threadDisposition, "reusable"); + assert.deepEqual( + [...latest.values()].map((item) => item.text), + terminalStatus === "completed" + ? [ + "Final summary one", + "Summary two", + "Raw trace", + "Completion without deltas", + "Retained when completion omits content", + ] + : ["Summary one", "Summary two", "Raw trace"], + ); + assert.isTrue([...latest.values()].every((item) => item.status === terminalStatus)); + assert.isTrue([...latest.values()].every((item) => item.streaming === false)); + assert.isTrue( + [...latest.values()].every((item) => item.runId !== null && item.providerTurnId !== null), + ); + assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, latest.size); + const command = harness.events.find( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "command_execution", + ); + assert.isDefined(command); + if (command?.type === "turn_item.updated") { + assert.isTrue( + [...latest.values()] + .slice(0, 3) + .every((item) => item.ordinal < command.turnItem.ordinal), + ); + } + assert.deepEqual(assistantMessages(harness.events), []); }).pipe( Effect.provide( Layer.mergeAll( @@ -4398,180 +4661,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ), - ), - ); - - it.effect.each(["completed", "interrupted"] as const)( - "retains Codex reasoning parts when the turn is %s", - (terminalStatus) => - Effect.scoped( - Effect.gen(function* () { - const scenario = `codex-reasoning-${terminalStatus}`; - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const prompt = "Explain the check."; - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), - ...[ - { - method: "item/reasoning/summaryTextDelta", - params: { itemId: "thought", summaryIndex: 0, delta: "Summary " }, - }, - { - method: "item/reasoning/summaryTextDelta", - params: { itemId: "thought", summaryIndex: 0, delta: "one" }, - }, - { - method: "item/reasoning/summaryTextDelta", - params: { itemId: "thought", summaryIndex: 1, delta: "Summary two" }, - }, - { - method: "item/reasoning/textDelta", - params: { itemId: "thought", contentIndex: 0, delta: "Raw trace" }, - }, - { - method: "item/completed", - params: { - item: { - type: "commandExecution", - id: "after-thought", - command: "pwd", - cwd: "/workspace", - processId: "42", - source: "unifiedExecStartup", - status: "completed", - commandActions: [{ type: "unknown", command: "pwd" }], - aggregatedOutput: "/workspace", - exitCode: 0, - durationMs: 1, - }, - }, - }, - ...(terminalStatus === "completed" - ? [ - { - method: "item/completed", - params: { - item: { - type: "reasoning", - id: "thought", - summary: ["Final summary one", "Summary two"], - content: ["Raw trace"], - }, - }, - }, - { - method: "item/completed", - params: { - item: { - type: "reasoning", - id: "completion-only", - summary: ["Completion without deltas"], - content: [], - }, - }, - }, - { - method: "item/reasoning/textDelta", - params: { - itemId: "delta-only", - contentIndex: 0, - delta: "Retained when completion omits content", - }, - }, - { - method: "item/completed", - params: { - item: { type: "reasoning", id: "delta-only", summary: [], content: [] }, - }, - }, - ] - : []), - ].map((event, index) => ({ - type: "emit_inbound" as const, - label: `reasoning-${index}`, - frame: { - method: event.method, - params: { threadId: nativeThreadId, turnId: nativeTurnId, ...event.params }, - }, - })), - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: terminalStatus }), - }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-${scenario}`), - text: prompt, - }), - ); - yield* harness.firstTerminal; - const latest = new Map( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "reasoning" - ? [[event.turnItem.id, event.turnItem] as const] - : [], - ), - ); - assert.deepEqual( - [...latest.values()].map((item) => item.text), - terminalStatus === "completed" - ? [ - "Final summary one", - "Summary two", - "Raw trace", - "Completion without deltas", - "Retained when completion omits content", - ] - : ["Summary one", "Summary two", "Raw trace"], - ); - assert.isTrue([...latest.values()].every((item) => item.status === terminalStatus)); - assert.isTrue([...latest.values()].every((item) => item.streaming === false)); - assert.isTrue( - [...latest.values()].every( - (item) => item.runId !== null && item.providerTurnId !== null, - ), - ); - assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, latest.size); - const command = harness.events.find( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "command_execution", - ); - assert.isDefined(command); - if (command?.type === "turn_item.updated") { - assert.isTrue( - [...latest.values()] - .slice(0, 3) - .every((item) => item.ordinal < command.turnItem.ordinal), - ); - } - assert.deepEqual(assistantMessages(harness.events), []); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), ); const finalAnswerTranscript = ( @@ -4677,106 +4766,104 @@ describe("CodexAdapterV2 post-settle continuation", () => { it.effect.each([false, true])( "preserves a final answer that repeats a preceding partial answer (streamed: %s)", (streamed) => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-partial-then-final", [ - { - id: "status", - text: "Checking the files", - phase: "commentary", - streamed, - }, - { - id: "partial", - text: "CODEX_RECOVERY_OK", - phase: "partial_answer", - streamed, - }, - { - id: "final", - text: "CODEX_RECOVERY_OK", - phase: "final_answer", - streamed, - }, - ]); - const gates = yield* Effect.forEach(["status", "partial", "final"], (id) => - Effect.gen(function* () { - return { - id, - ready: yield* Deferred.make(), - release: yield* Deferred.make(), - }; - }), - ); - const harness = yield* makeCodexReplayHarness( - transcript, - undefined, - undefined, - undefined, - (entry) => { - const gate = streamed - ? gates.find((gate) => entry.label === `item/completed/${gate.id}`) - : undefined; - return gate === undefined - ? Effect.void - : Deferred.succeed(gate.ready, undefined).pipe( - Effect.andThen(Deferred.await(gate.release)), - ); - }, - ); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-partial-then-final"), - text: "Reply with the requested recovery marker.", - }), - ); - if (streamed) { - for (const gate of gates) { - yield* Deferred.await(gate.ready); - yield* TestClock.adjust("50 millis"); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.nativeItemRef?.nativeId === gate.id && - event.turnItem.streaming, - ), - ); - yield* Deferred.succeed(gate.release, undefined); - } - } - yield* harness.awaitTerminal(1); - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["Checking the files", "CODEX_RECOVERY_OK", "CODEX_RECOVERY_OK"], - ); - const updates = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" - ? [event.turnItem] - : [], - ); - for (const [text, phase] of [ - ["Checking the files", "commentary"], - ["CODEX_RECOVERY_OK", "partial_answer"], - ["CODEX_RECOVERY_OK", "final_answer"], - ]) { - const matching = updates.filter((item) => item.text === text && item.phase === phase); - assert.isTrue(matching.some((item) => !item.streaming)); - if (streamed) assert.isTrue(matching.some((item) => item.streaming)); + Effect.gen(function* () { + const transcript = finalAnswerTranscript("codex-partial-then-final", [ + { + id: "status", + text: "Checking the files", + phase: "commentary", + streamed, + }, + { + id: "partial", + text: "CODEX_RECOVERY_OK", + phase: "partial_answer", + streamed, + }, + { + id: "final", + text: "CODEX_RECOVERY_OK", + phase: "final_answer", + streamed, + }, + ]); + const gates = yield* Effect.forEach(["status", "partial", "final"], (id) => + Effect.gen(function* () { + return { + id, + ready: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + }), + ); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + (entry) => { + const gate = streamed + ? gates.find((gate) => entry.label === `item/completed/${gate.id}`) + : undefined; + return gate === undefined + ? Effect.void + : Deferred.succeed(gate.ready, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + ); + }, + ); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-partial-then-final"), + text: "Reply with the requested recovery marker.", + }), + ); + if (streamed) { + for (const gate of gates) { + yield* Deferred.await(gate.ready); + yield* TestClock.adjust("50 millis"); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.nativeItemRef?.nativeId === gate.id && + event.turnItem.streaming, + ), + ); + yield* Deferred.succeed(gate.release, undefined); } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + yield* harness.awaitTerminal(1); + assert.deepEqual( + assistantMessages(harness.events).map((event) => event.message.text), + ["Checking the files", "CODEX_RECOVERY_OK", "CODEX_RECOVERY_OK"], + ); + const updates = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" + ? [event.turnItem] + : [], + ); + for (const [text, phase] of [ + ["Checking the files", "commentary"], + ["CODEX_RECOVERY_OK", "partial_answer"], + ["CODEX_RECOVERY_OK", "final_answer"], + ]) { + const matching = updates.filter((item) => item.text === text && item.phase === phase); + assert.isTrue(matching.some((item) => !item.streaming)); + if (streamed) assert.isTrue(matching.some((item) => item.streaming)); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -5059,43 +5146,41 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ), - ); - - it.effect("suppresses a trailing empty final answer after a non-empty final answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-redundant-empty-final", [ - { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" }, - { id: "answer-empty", text: "" }, - ]); - const harness = yield* makeCodexReplayHarness(transcript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-redundant-empty-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* harness.awaitTerminal(1); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), + ); + + it.effect("suppresses a trailing empty final answer after a non-empty final answer", () => + Effect.gen(function* () { + const transcript = finalAnswerTranscript("codex-redundant-empty-final", [ + { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" }, + { id: "answer-empty", text: "" }, + ]); + const harness = yield* makeCodexReplayHarness(transcript); + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-redundant-empty-final"), + text: "Reply with the requested recovery marker.", + }), + ); + yield* harness.awaitTerminal(1); + + assert.deepEqual( + assistantMessages(harness.events).map((event) => event.message.text), + ["CODEX_RECOVERY_OK"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); @@ -5235,52 +5320,50 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect("wakes with well-formed text when the cuts split an emoji", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness( - makeCodexReplayTranscript({ - scenario: "codex-bg-wake-surrogate", - entries: [ - ...backgroundExecTranscript.entries.slice(0, -1), - { - type: "emit_inbound", - label: "item/completed/command-late", - frame: { - method: "item/completed", - params: { - item: { - ...backgroundCommandItem("completed"), - command: `${"c".repeat(199)}🚀`, - aggregatedOutput: `🚀${"x".repeat(999)}\n`, - }, - threadId: BG_NATIVE_THREAD, - turnId: BG_NATIVE_TURN, - completedAtMs: 1782622465500, + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-bg-wake-surrogate", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -1), + { + type: "emit_inbound", + label: "item/completed/command-late", + frame: { + method: "item/completed", + params: { + item: { + ...backgroundCommandItem("completed"), + command: `${"c".repeat(199)}🚀`, + aggregatedOutput: `🚀${"x".repeat(999)}\n`, }, + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + completedAtMs: 1782622465500, }, }, - ], - }), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-codex-bg-wake-surrogate"), - text: BG_PROMPT, - }), - ); - yield* harness.until(() => harness.continuationRequests.length > 0); - assert.isTrue(harness.continuationRequests[0]?.detail?.isWellFormed()); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + }, + ], + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-bg-wake-surrogate"), + text: BG_PROMPT, + }), + ); + yield* harness.until(() => harness.continuationRequests.length > 0); + assert.isTrue(harness.continuationRequests[0]?.detail?.isWellFormed()); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -5515,67 +5598,65 @@ describe("CodexAdapterV2 post-settle continuation", () => { (terminated) => { const stillRunning = terminated === "still_running"; const transcript = makeBackgroundStopTranscript(terminated); - return Effect.scoped( - Effect.gen(function* () { - const stopped = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness(transcript, (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "interrupted" - ? Deferred.succeed(stopped, undefined) - : Effect.void, - ); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, + return Effect.gen(function* () { + const stopped = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness(transcript, (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "interrupted" + ? Deferred.succeed(stopped, undefined) + : Effect.void, + ); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-bg-stop"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]!; + assert.equal(terminal.status, "completed"); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + assert.isFalse( + yield* harness.runtime.hasPendingBackgroundWorkForThread!({ + ...harness.providerThread, + id: ProviderThreadId.make("unrelated-provider-thread"), + }), + ); + if (stillRunning) { + const failed = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-bg-stop"), - text: BG_PROMPT, - }), - ); - yield* harness.firstTerminal; - const terminal = harness.terminalEvents()[0]!; - assert.equal(terminal.status, "completed"); + providerTurnId: terminal.providerTurnId, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.equal(failed._tag, "Failure"); assert.isTrue(yield* harness.hasPendingBackgroundWork); - assert.isFalse( - yield* harness.runtime.hasPendingBackgroundWorkForThread!({ - ...harness.providerThread, - id: ProviderThreadId.make("unrelated-provider-thread"), - }), - ); - if (stillRunning) { - const failed = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: terminal.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.exit); - assert.equal(failed._tag, "Failure"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - } - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: stillRunning - ? ProviderTurnId.make("later-completed-turn") - : terminal.providerTurnId, - requestRuntimeRestart: true, - }); - yield* Deferred.await(stopped); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.terminalEvents(), 1); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.lengthOf(harness.continuationRequests, 0); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: stillRunning + ? ProviderTurnId.make("later-completed-turn") + : terminal.providerTurnId, + requestRuntimeRestart: true, + }); + yield* Deferred.await(stopped); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.terminalEvents(), 1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.lengthOf(harness.continuationRequests, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ); @@ -5583,246 +5664,242 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); it.effect("stops a completed run's background command without a client-supplied run", () => { const transcript = makeBackgroundStopTranscript(true); - return Effect.scoped( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" }); - const localTranscript = yield* decodeReplayTranscriptJson( - (yield* encodeReplayTranscriptJson(transcript)).replaceAll( - yield* encodeStringJson("/workspace"), - yield* encodeStringJson(cwd), + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" }); + const localTranscript = yield* decodeReplayTranscriptJson( + (yield* encodeReplayTranscriptJson(transcript)).replaceAll( + yield* encodeStringJson("/workspace"), + yield* encodeStringJson(cwd), + ), + ); + const replayDriver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + assert.equal( + Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))), + 0, + ); + assert.equal( + Number( + yield* spawner.exitCode( + ChildProcess.make( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "--quiet", + "-m", + "Initial commit", + ], + { cwd }, + ), + ), + ), + 0, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:background-stop"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-background-stop"), + threadId, + projectId: ProjectId.make("project:background-stop"), + title: "Background stop", + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const waiting = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "run.updated" && event.payload.status === "waiting", ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), ); - const replayDriver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript)); - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-background-stop"), + threadId, + messageId: MessageId.make("message:background-stop"), + text: BG_PROMPT, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + assert.isNull((yield* Ref.get(replayDriver.state)).failure); + yield* Fiber.join(waiting); + yield* worker.drain(); + const projection = yield* orchestrator.getThreadProjection(threadId); + const run = projection.runs.at(-1)!; + assert.equal(run.status, "completed"); assert.equal( - Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))), - 0, + (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length, + 1, ); - assert.equal( - Number( - yield* spawner.exitCode( - ChildProcess.make( - "git", - [ - "-c", - "user.name=Test", - "-c", - "user.email=test@example.com", - "commit", - "--allow-empty", - "--quiet", - "-m", - "Initial commit", - ], - { cwd }, - ), - ), + const stopped = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "turn-item.updated" && + event.payload.type === "command_execution" && + event.payload.status === "interrupted", ), - 0, + Stream.runHead, + Effect.forkChild({ startImmediately: true }), ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = ThreadId.make("thread:background-stop"); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create-background-stop"), - threadId, - projectId: ProjectId.make("project:background-stop"), - title: "Background stop", - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - const waiting = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("start-background-stop"), - threadId, - messageId: MessageId.make("message:background-stop"), - text: BG_PROMPT, - attachments: [], - createdBy: "user", - creationSource: "web", - dispatchMode: { type: "start_immediately" }, - }); - yield* worker.drain(); - assert.isNull((yield* Ref.get(replayDriver.state)).failure); - yield* Fiber.join(waiting); - yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - const run = projection.runs.at(-1)!; - assert.equal(run.status, "completed"); - assert.equal( - (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length, - 1, - ); - const stopped = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "turn-item.updated" && - event.payload.type === "command_execution" && - event.payload.status === "interrupted", - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* orchestrator.dispatch({ - type: "thread.stop", - commandId: CommandId.make("stop-background-command"), - threadId, - }); - yield* worker.drain(); - yield* Fiber.join(stopped); - assert.equal( - (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status, - "completed", - ); - assert.deepEqual( - (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, - [], - ); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { name: "codex-background-stop", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ - transcript: localTranscript, - driver: replayDriver, - }), - { runEffectWorker: false }, - ), + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-background-command"), + threadId, + }); + yield* worker.drain(); + yield* Fiber.join(stopped); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status, + "completed", + ); + assert.deepEqual( + (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, + [], + ); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "codex-background-stop", runtimePolicyOverride: { cwd } }, + CodexAdapterV2Testkit.layer({ + transcript: localTranscript, + driver: replayDriver, + }), + { runEffectWorker: false }, + ), + ), + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + }); + + it.effect("Stop ends a background command no Codex process tracks any more", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stale-workspace-" }); + const staleTranscript = makeCodexReplayTranscript({ + scenario: "codex-bg-stop-untracked", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -1), + { type: "runtime_exit", status: "success" }, + ], + }); + const localTranscript = yield* decodeReplayTranscriptJson( + (yield* encodeReplayTranscriptJson(staleTranscript)).replaceAll( + yield* encodeStringJson("/workspace"), + yield* encodeStringJson(cwd), + ), + ); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + for (const args of [ + ["init", "--quiet"], + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "--quiet", + "-m", + "Initial commit", + ], + ]) { + assert.equal(Number(yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }))), 0); + } + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:background-stop-untracked"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-background-stop-untracked"), + threadId, + projectId: ProjectId.make("project:background-stop-untracked"), + title: "Background stop untracked", + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + (event.payload.status === "waiting" || event.payload.status === "completed"), ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), ); - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - }); - - it.effect("Stop ends a background command no Codex process tracks any more", () => - Effect.scoped( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stale-workspace-" }); - const staleTranscript = makeCodexReplayTranscript({ - scenario: "codex-bg-stop-untracked", - entries: [ - ...backgroundExecTranscript.entries.slice(0, -1), - { type: "runtime_exit", status: "success" }, - ], + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-background-stop-untracked"), + threadId, + messageId: MessageId.make("message:background-stop-untracked"), + text: BG_PROMPT, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, }); - const localTranscript = yield* decodeReplayTranscriptJson( - (yield* encodeReplayTranscriptJson(staleTranscript)).replaceAll( - yield* encodeStringJson("/workspace"), - yield* encodeStringJson(cwd), + yield* worker.drain(); + yield* Fiber.join(settled); + yield* worker.drain(); + const before = yield* orchestrator.getThreadShell(threadId); + assert.deepEqual( + before?.pendingBackgroundTasks?.map((task) => task.kind), + ["command"], + "the thread still shows the command the gone process never finished", + ); + const run = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!; + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop-background-untracked"), + threadId, + runId: run.id, + holdQueue: true, + }); + yield* worker.drain(); + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + projection.turnItems.flatMap((item) => + item.type === "command_execution" ? [item.status] : [], ), + ["interrupted"], ); - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - for (const args of [ - ["init", "--quiet"], - [ - "-c", - "user.name=Test", - "-c", - "user.email=test@example.com", - "commit", - "--allow-empty", - "--quiet", - "-m", - "Initial commit", - ], - ]) { - assert.equal(Number(yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }))), 0); - } - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = ThreadId.make("thread:background-stop-untracked"); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create-background-stop-untracked"), - threadId, - projectId: ProjectId.make("project:background-stop-untracked"), - title: "Background stop untracked", - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - const settled = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - (event.payload.status === "waiting" || event.payload.status === "completed"), - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("start-background-stop-untracked"), - threadId, - messageId: MessageId.make("message:background-stop-untracked"), - text: BG_PROMPT, - attachments: [], - createdBy: "user", - creationSource: "web", - dispatchMode: { type: "start_immediately" }, - }); - yield* worker.drain(); - yield* Fiber.join(settled); - yield* worker.drain(); - const before = yield* orchestrator.getThreadShell(threadId); - assert.deepEqual( - before?.pendingBackgroundTasks?.map((task) => task.kind), - ["command"], - "the thread still shows the command the gone process never finished", - ); - const run = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!; - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("stop-background-untracked"), - threadId, - runId: run.id, - holdQueue: true, - }); - yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual( - projection.turnItems.flatMap((item) => - item.type === "command_execution" ? [item.status] : [], - ), - ["interrupted"], - ); - assert.equal(projection.runs.at(-1)?.status, "completed"); - assert.deepEqual( - (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, - [], - ); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { name: "codex-background-stop-untracked", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ transcript: withConfigReads(localTranscript) }), - { runEffectWorker: false }, - ), - ), + assert.equal(projection.runs.at(-1)?.status, "completed"); + assert.deepEqual( + (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, + [], ); - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ), + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "codex-background-stop-untracked", runtimePolicyOverride: { cwd } }, + CodexAdapterV2Testkit.layer({ transcript: withConfigReads(localTranscript) }), + { runEffectWorker: false }, + ), + ), + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); const INTERRUPT_SCENARIO = "codex-interrupt-mid-command"; @@ -5983,133 +6060,131 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); it.effect("contains commands that start before and after the interrupt response", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptMidCommandTranscript); - const now = yield* DateTime.now; + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness(interruptMidCommandTranscript); + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-mid-command"), - text: INTERRUPT_PROMPT, - }), - ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-interrupt-mid-command"), + text: INTERRUPT_PROMPT, + }), + ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "running", - ), - ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "running", + ), + ); - const providerTurnId = harness.events.find( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_turn.updated" } - > => event.type === "provider_turn.updated", - )?.providerTurn.id; - assert.isDefined(providerTurnId); + const providerTurnId = harness.events.find( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_turn.updated" } + > => event.type === "provider_turn.updated", + )?.providerTurn.id; + assert.isDefined(providerTurnId); + + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, + }); - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }); + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); + const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); + assert.isAtLeast(terminalIndex, 0); - const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); - assert.isAtLeast(terminalIndex, 0); - - let lastCommandBeforeTerminal: - | Extract - | undefined; - for (let index = 0; index < terminalIndex; index++) { - const event = harness.events[index]; - if (event?.type === "turn_item.updated" && event.turnItem.type === "command_execution") { - lastCommandBeforeTerminal = event; - } + let lastCommandBeforeTerminal: + | Extract + | undefined; + for (let index = 0; index < terminalIndex; index++) { + const event = harness.events[index]; + if (event?.type === "turn_item.updated" && event.turnItem.type === "command_execution") { + lastCommandBeforeTerminal = event; } - assert.isDefined(lastCommandBeforeTerminal); - assert.equal(lastCommandBeforeTerminal.turnItem.status, "interrupted"); - assert.isNotNull(lastCommandBeforeTerminal.turnItem.completedAt); + } + assert.isDefined(lastCommandBeforeTerminal); + assert.equal(lastCommandBeforeTerminal.turnItem.status, "interrupted"); + assert.isNotNull(lastCommandBeforeTerminal.turnItem.completedAt); - const interruptedCommandsBeforeTerminal = harness.events - .slice(0, terminalIndex) - .flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "interrupted" - ? [event.turnItem.input] - : [], - ) - .sort(); - assert.deepEqual( - interruptedCommandsBeforeTerminal, - [INTERRUPT_COMMAND, INTERRUPT_COMMAND_TWO].sort(), - ); + const interruptedCommandsBeforeTerminal = harness.events + .slice(0, terminalIndex) + .flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "interrupted" + ? [event.turnItem.input] + : [], + ) + .sort(); + assert.deepEqual( + interruptedCommandsBeforeTerminal, + [INTERRUPT_COMMAND, INTERRUPT_COMMAND_TWO].sort(), + ); - const interruptedCommandIndex = harness.events.findIndex( - (event, index) => - index < terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "interrupted", - ); - assert.isAbove( - terminalIndex, - interruptedCommandIndex, - "command terminalization must precede turn.terminal", - ); + const interruptedCommandIndex = harness.events.findIndex( + (event, index) => + index < terminalIndex && + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "interrupted", + ); + assert.isAbove( + terminalIndex, + interruptedCommandIndex, + "command terminalization must precede turn.terminal", + ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.continuationRequests, 0); - yield* TestClock.adjust("30 seconds"); - for (let attempt = 0; attempt < 100; attempt++) { - yield* Effect.yieldNow; - } - assert.lengthOf(harness.continuationRequests, 0); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.terminalEvents(), 1); + yield* TestClock.adjust("30 seconds"); + for (let attempt = 0; attempt < 100; attempt++) { + yield* Effect.yieldNow; + } + assert.lengthOf(harness.continuationRequests, 0); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.terminalEvents(), 1); - const postTerminalCommandUpdates = harness.events.filter( - (event, index) => - index > terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution", - ); - assert.lengthOf( - postTerminalCommandUpdates, - 0, - "late item/completed after interrupt must not project", - ); + const postTerminalCommandUpdates = harness.events.filter( + (event, index) => + index > terminalIndex && + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution", + ); + assert.lengthOf( + postTerminalCommandUpdates, + 0, + "late item/completed after interrupt must not project", + ); - const commandUpdates = harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "turn_item.updated" } - > => event.type === "turn_item.updated" && event.turnItem.type === "command_execution", - ); - assert.isAtLeast(commandUpdates.length, 2, "start + interrupt terminalization"); - assert.equal(commandUpdates[commandUpdates.length - 1]?.turnItem.status, "interrupted"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const commandUpdates = harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "turn_item.updated" } + > => event.type === "turn_item.updated" && event.turnItem.type === "command_execution", + ); + assert.isAtLeast(commandUpdates.length, 2, "start + interrupt terminalization"); + assert.equal(commandUpdates[commandUpdates.length - 1]?.turnItem.status, "interrupted"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -6282,75 +6357,73 @@ describe("CodexAdapterV2 post-settle continuation", () => { }; it.effect("contains descendant commands and keeps Stop authoritative", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptSubagentCommandTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-command"), - text: INTERRUPT_PROMPT, - }), - ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && - event.turnItem.status === "running", - ), - ); - const providerTurnId = harness.events.find( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_turn.updated" } - > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, - )?.providerTurn.id; - assert.isDefined(providerTurnId); - - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }); + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness(interruptSubagentCommandTranscript); + const now = yield* DateTime.now; - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - const childCommandUpdates = harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "turn_item.updated" } - > => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM, - ); - assert.equal(childCommandUpdates.at(-1)?.turnItem.status, "interrupted"); - assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "interrupted"); - assert.isDefined( - harness - .subagentUpdates() - .find((event) => event.subagent.status === "running" && event.subagent.progress), - "a running native subagent reports its child's current command as progress", - ); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-command"), + text: INTERRUPT_PROMPT, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && + event.turnItem.status === "running", + ), + ); + const providerTurnId = harness.events.find( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_turn.updated" } + > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, + )?.providerTurn.id; + assert.isDefined(providerTurnId); + + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, + }); + + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); + const childCommandUpdates = harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "turn_item.updated" } + > => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM, + ); + assert.equal(childCommandUpdates.at(-1)?.turnItem.status, "interrupted"); + assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "interrupted"); + assert.isDefined( + harness + .subagentUpdates() + .find((event) => event.subagent.status === "running" && event.subagent.progress), + "a running native subagent reports its child's current command as progress", + ); + assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -6400,73 +6473,71 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); it.effect("interrupts descendants that start after the initial Stop snapshot", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptLateSubagentTurnTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-late-subagent-turn"), - text: INTERRUPT_PROMPT, - }), - ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && - event.turnItem.status === "running", - ), - ); - const providerTurnId = harness.events.find( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_turn.updated" } - > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, - )?.providerTurn.id; - assert.isDefined(providerTurnId); - - const interruptFiber = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, - ), - ); - yield* Fiber.join(interruptFiber); + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness(interruptLateSubagentTurnTranscript); + const now = yield* DateTime.now; - yield* harness.awaitTerminal(1); - const lateChildUpdates = harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_turn.updated" } - > => + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-interrupt-late-subagent-turn"), + text: INTERRUPT_PROMPT, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && + event.turnItem.status === "running", + ), + ); + const providerTurnId = harness.events.find( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_turn.updated" } + > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, + )?.providerTurn.id; + assert.isDefined(providerTurnId); + + const interruptFiber = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* harness.until(() => + harness.events.some( + (event) => event.type === "provider_turn.updated" && event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, - ); - assert.equal(lateChildUpdates.at(-1)?.providerTurn.status, "interrupted"); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + ), + ); + yield* Fiber.join(interruptFiber); + + yield* harness.awaitTerminal(1); + const lateChildUpdates = harness.events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_turn.updated" } + > => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, + ); + assert.equal(lateChildUpdates.at(-1)?.providerTurn.status, "interrupted"); + assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -6535,69 +6606,67 @@ describe("CodexAdapterV2 post-settle continuation", () => { it.effect( "keeps reading notifications while interrupting a child turn that starts after Stop", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptSubagentTurnAfterStopTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-turn-after-stop"), - text: INTERRUPT_PROMPT, - }), - ); - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && - event.turnItem.status === "running", - ), - ); - const providerTurnId = harness.events.find( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "provider_turn.updated" } - > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, - )?.providerTurn.id; - assert.isDefined(providerTurnId); + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness(interruptSubagentTurnAfterStopTranscript); + const now = yield* DateTime.now; - yield* harness.runtime.interruptTurn({ + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, providerThread: harness.providerThread, - providerTurnId, - }); - yield* harness.awaitTerminal(1); + now, + attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-turn-after-stop"), + text: INTERRUPT_PROMPT, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && + event.turnItem.status === "running", + ), + ); + const providerTurnId = harness.events.find( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "provider_turn.updated" } + > => event.type === "provider_turn.updated" && event.threadId === harness.threadId, + )?.providerTurn.id; + assert.isDefined(providerTurnId); - // The TestClock never reaches the interrupt's timeout, so this arrives only - // if the reader is free to read the interrupt response and the frame after it. - yield* harness.until(() => - harness.events.some( - (event) => - event.type === "provider_thread.updated" && - event.providerThread.goal?.status === "paused", - ), - ); - assert.isFalse( - harness.events.some( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, + }); + yield* harness.awaitTerminal(1); + + // The TestClock never reaches the interrupt's timeout, so this arrives only + // if the reader is free to read the interrupt response and the frame after it. + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.goal?.status === "paused", + ), + ); + assert.isFalse( + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -6772,354 +6841,352 @@ describe("CodexAdapterV2 post-settle continuation", () => { expectedMessage: "namespace", }, ] as const)("classifies Codex terminal failures from $name evidence", (scenario) => - Effect.scoped( - Effect.gen(function* () { - const nativeThreadId = `native-limit-${scenario.name}`; - const nativeTurnId = `turn-limit-${scenario.name}`; - const message = "message" in scenario ? scenario.message : "Provider stopped this request."; - const errorInfo = "errorInfo" in scenario ? scenario.errorInfo : scenario.code; - const resetAt = "2033-05-19T07:20:00.000Z"; - const snapshot = { - type: "emit_inbound" as const, - label: "account/rateLimits/updated", - frame: { - method: "account/rateLimits/updated", - params: { - rateLimits: { - limitId: "codex", - primary: { usedPercent: 100, resetsAt: 2000100000, windowDurationMins: 300 }, - }, + Effect.gen(function* () { + const nativeThreadId = `native-limit-${scenario.name}`; + const nativeTurnId = `turn-limit-${scenario.name}`; + const message = "message" in scenario ? scenario.message : "Provider stopped this request."; + const errorInfo = "errorInfo" in scenario ? scenario.errorInfo : scenario.code; + const resetAt = "2033-05-19T07:20:00.000Z"; + const snapshot = { + type: "emit_inbound" as const, + label: "account/rateLimits/updated", + frame: { + method: "account/rateLimits/updated", + params: { + rateLimits: { + limitId: "codex", + primary: { usedPercent: 100, resetsAt: 2000100000, windowDurationMins: 300 }, }, }, - }; - const readsReset = - scenario.name === "first-request-reset" || scenario.name === "newer-reset-during-read"; - // Usage limits with no known reset read the account before publishing their terminal. - const readsAccount = - scenario.expectedClass === "usage_limit" && - !("expectedCode" in scenario) && - scenario.name !== "deferred-reset"; - const premium = { - ...snapshot, - frame: { - method: "account/rateLimits/updated", - params: { rateLimits: { limitId: "premium", primary: null, secondary: null } }, - }, - }; - const newerSnapshot = { - ...snapshot, - frame: { - method: "account/rateLimits/updated", - params: { - rateLimits: { - limitId: "codex", - primary: { usedPercent: 100, resetsAt: 2000200000, windowDurationMins: 300 }, - }, + }, + }; + const readsReset = + scenario.name === "first-request-reset" || scenario.name === "newer-reset-during-read"; + // Usage limits with no known reset read the account before publishing their terminal. + const readsAccount = + scenario.expectedClass === "usage_limit" && + !("expectedCode" in scenario) && + scenario.name !== "deferred-reset"; + const premium = { + ...snapshot, + frame: { + method: "account/rateLimits/updated", + params: { rateLimits: { limitId: "premium", primary: null, secondary: null } }, + }, + }; + const newerSnapshot = { + ...snapshot, + frame: { + method: "account/rateLimits/updated", + params: { + rateLimits: { + limitId: "codex", + primary: { usedPercent: 100, resetsAt: 2000200000, windowDurationMins: 300 }, }, }, - }; - const readRequest = { - type: "expect_outbound" as const, - label: "account/rateLimits/read", - frame: { id: 4, method: "account/rateLimits/read", params: null }, - }; - const transcript = makeCodexReplayTranscript({ - scenario: `codex-limit-${scenario.name}`, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - ...("usedBefore" in scenario - ? [ - { - ...snapshot, - frame: { - method: "account/rateLimits/updated", - params: { - rateLimits: { - limitId: "codex", - primary: { - usedPercent: scenario.usedBefore, - resetsAt: 2000100000, - windowDurationMins: 300, - }, - }, - }, - }, - }, - ] - : []), - ...(readsReset ? [premium] : []), - // A file change that starts never reaches the projection when the turn then fails. - ...("workBefore" in scenario - ? [ - { - type: "emit_inbound" as const, - label: "item/started/fileChange", - frame: { - method: "item/started", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - startedAtMs: 1, - item: { - type: "fileChange", - id: "limit-file-change", - status: "inProgress", - changes: [], - }, - }, - }, - }, - ] - : []), - ...(scenario.name === "deferred-reset" ? [snapshot] : []), - ...(scenario.name === "deferred-reset" - ? [ - { - type: "emit_inbound" as const, - label: "item/completed/subAgentActivity-started", - frame: { - method: "item/completed", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - item: { - type: "subAgentActivity", - id: "limit-child-spawn", - kind: "started", - agentThreadId: "native-limit-child", - agentPath: "/root/limit_child", + }, + }; + const readRequest = { + type: "expect_outbound" as const, + label: "account/rateLimits/read", + frame: { id: 4, method: "account/rateLimits/read", params: null }, + }; + const transcript = makeCodexReplayTranscript({ + scenario: `codex-limit-${scenario.name}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + ...("usedBefore" in scenario + ? [ + { + ...snapshot, + frame: { + method: "account/rateLimits/updated", + params: { + rateLimits: { + limitId: "codex", + primary: { + usedPercent: scenario.usedBefore, + resetsAt: 2000100000, + windowDurationMins: 300, }, }, }, }, - { - type: "emit_inbound" as const, - label: "turn/started/child", - frame: { - method: "turn/started", - params: { - threadId: "native-limit-child", - turn: makeCodexReplayTurn({ - id: "limit-child-turn", - status: "inProgress", - }), + }, + ] + : []), + ...(readsReset ? [premium] : []), + // A file change that starts never reaches the projection when the turn then fails. + ...("workBefore" in scenario + ? [ + { + type: "emit_inbound" as const, + label: "item/started/fileChange", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1, + item: { + type: "fileChange", + id: "limit-file-change", + status: "inProgress", + changes: [], }, }, }, - ] - : []), - ...(scenario.notification - ? [ - { - type: "emit_inbound" as const, - label: "error", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: scenario.name === "retry" || "willRetry" in scenario, - error: { - message, - codexErrorInfo: errorInfo, - additionalDetails: - "details" in scenario - ? scenario.details - : scenario.name === "matching-details" - ? "Detailed provider allowance explanation." - : null, - }, + }, + ] + : []), + ...(scenario.name === "deferred-reset" ? [snapshot] : []), + ...(scenario.name === "deferred-reset" + ? [ + { + type: "emit_inbound" as const, + label: "item/completed/subAgentActivity-started", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + item: { + type: "subAgentActivity", + id: "limit-child-spawn", + kind: "started", + agentThreadId: "native-limit-child", + agentPath: "/root/limit_child", }, }, }, - ] - : []), - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), - error: { - message: scenario.name === "replacement" ? "A different failure." : message, - ...(scenario.notification && - scenario.name !== "matching-details" && - !("details" in scenario) - ? {} - : { codexErrorInfo: errorInfo }), + }, + { + type: "emit_inbound" as const, + label: "turn/started/child", + frame: { + method: "turn/started", + params: { + threadId: "native-limit-child", + turn: makeCodexReplayTurn({ + id: "limit-child-turn", + status: "inProgress", + }), }, }, }, - }, - }, - ...(readsAccount ? [readRequest] : []), - ...(scenario.name === "newer-reset-during-read" ? [newerSnapshot] : []), - ...(readsReset - ? [ - { - type: "emit_inbound" as const, - label: "account/rateLimits/read", - frame: { - id: 4, - result: { - ...premium.frame.params, - rateLimitsByLimitId: { codex: snapshot.frame.params.rateLimits }, + ] + : []), + ...(scenario.notification + ? [ + { + type: "emit_inbound" as const, + label: "error", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: scenario.name === "retry" || "willRetry" in scenario, + error: { + message, + codexErrorInfo: errorInfo, + additionalDetails: + "details" in scenario + ? scenario.details + : scenario.name === "matching-details" + ? "Detailed provider allowance explanation." + : null, }, }, }, - ] - : []), - ...(readsAccount && !readsReset - ? [ - { - type: "emit_inbound" as const, - label: "account/rateLimits/read", - frame: { id: 4, error: { code: -32600, message: "Not signed in." } }, + }, + ] + : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), + error: { + message: scenario.name === "replacement" ? "A different failure." : message, + ...(scenario.notification && + scenario.name !== "matching-details" && + !("details" in scenario) + ? {} + : { codexErrorInfo: errorInfo }), }, - ] - : []), - ...(scenario.name === "late-reset" - ? [{ ...snapshot, label: "account/rateLimits/updated/late" }] - : []), - ...("resetAfter" in scenario ? [snapshot] : []), - ...(scenario.name === "deferred-reset" - ? [ - { - ...snapshot, - frame: { - method: "account/rateLimits/updated", - params: { - rateLimits: { - limitId: "codex", - primary: { - usedPercent: 100, - resetsAt: 2000200000, - windowDurationMins: 300, - }, + }, + }, + }, + }, + ...(readsAccount ? [readRequest] : []), + ...(scenario.name === "newer-reset-during-read" ? [newerSnapshot] : []), + ...(readsReset + ? [ + { + type: "emit_inbound" as const, + label: "account/rateLimits/read", + frame: { + id: 4, + result: { + ...premium.frame.params, + rateLimitsByLimitId: { codex: snapshot.frame.params.rateLimits }, + }, + }, + }, + ] + : []), + ...(readsAccount && !readsReset + ? [ + { + type: "emit_inbound" as const, + label: "account/rateLimits/read", + frame: { id: 4, error: { code: -32600, message: "Not signed in." } }, + }, + ] + : []), + ...(scenario.name === "late-reset" + ? [{ ...snapshot, label: "account/rateLimits/updated/late" }] + : []), + ...("resetAfter" in scenario ? [snapshot] : []), + ...(scenario.name === "deferred-reset" + ? [ + { + ...snapshot, + frame: { + method: "account/rateLimits/updated", + params: { + rateLimits: { + limitId: "codex", + primary: { + usedPercent: 100, + resetsAt: 2000200000, + windowDurationMins: 300, }, }, }, }, - { - type: "emit_inbound" as const, - label: "turn/completed/child", - frame: { - method: "turn/completed", - params: { - threadId: "native-limit-child", - turn: makeCodexReplayTurn({ - id: "limit-child-turn", - status: "completed", - }), - }, + }, + { + type: "emit_inbound" as const, + label: "turn/completed/child", + frame: { + method: "turn/completed", + params: { + threadId: "native-limit-child", + turn: makeCodexReplayTurn({ + id: "limit-child-turn", + status: "completed", + }), }, }, - ] - : []), - ], - }); - const resetReceipt = yield* Deferred.make(); - const snapshotReceipt = yield* Deferred.make(); - const terminalReceipt = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness( - transcript, - (event) => - event.type === "turn.terminal" - ? Deferred.succeed(terminalReceipt, undefined) - : event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.failure.resetAt === resetAt - ? Deferred.succeed(resetReceipt, undefined) - : Effect.void, - undefined, - undefined, - // The late reset must land after the terminal its failed read released. - (entry) => - entry.label === "account/rateLimits/updated/late" - ? Deferred.await(terminalReceipt) - : Effect.void, - () => Deferred.succeed(snapshotReceipt, undefined), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - text: "Continue.", - attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`), - }), - ); - yield* harness.firstTerminal; - const terminal = harness.terminalEvents()[0]; - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.equal(terminal.failure.class, scenario.expectedClass); - assert.equal(terminal.threadDisposition, "reusable"); - assert.equal( - terminal.accountFailure, - scenario.expectedClass === "usage_limit" - ? "usage_limit" - : scenario.name === "sharing-sign-in" - ? "auth" - : undefined, - ); - // A child started or a file change began: the turn did work, so it never fails over. - assert.equal( - terminal.noWorkObserved, - "workBefore" in scenario || scenario.name === "deferred-reset" ? undefined : true, - ); - if (scenario.name === "deferred-reset" || scenario.name === "first-request-reset") - assert.equal(terminal.failure.resetAt, resetAt); - if (scenario.name === "newer-reset-during-read") - assert.equal(terminal.failure.resetAt, "2033-05-20T11:06:40.000Z"); - if (scenario.name === "matching-details") - assert.equal(terminal.failure.message, "Detailed provider allowance explanation."); - if ("resetAfter" in scenario) { - yield* Deferred.await(snapshotReceipt); - assert.isFalse( - harness.events.some( - (event) => - event.type === "turn_item.updated" && + }, + ] + : []), + ], + }); + const resetReceipt = yield* Deferred.make(); + const snapshotReceipt = yield* Deferred.make(); + const terminalReceipt = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + transcript, + (event) => + event.type === "turn.terminal" + ? Deferred.succeed(terminalReceipt, undefined) + : event.type === "turn_item.updated" && event.turnItem.type === "error" && - event.turnItem.failure.resetAt != null, - ), - ); - } - if (scenario.name === "late-reset") { - yield* Deferred.await(resetReceipt); - const item = harness.events.find( + event.turnItem.failure.resetAt === resetAt + ? Deferred.succeed(resetReceipt, undefined) + : Effect.void, + undefined, + undefined, + // The late reset must land after the terminal its failed read released. + (entry) => + entry.label === "account/rateLimits/updated/late" + ? Deferred.await(terminalReceipt) + : Effect.void, + () => Deferred.succeed(snapshotReceipt, undefined), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`), + }), + ); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.class, scenario.expectedClass); + assert.equal(terminal.threadDisposition, "reusable"); + assert.equal( + terminal.accountFailure, + scenario.expectedClass === "usage_limit" + ? "usage_limit" + : scenario.name === "sharing-sign-in" + ? "auth" + : undefined, + ); + // A child started or a file change began: the turn did work, so it never fails over. + assert.equal( + terminal.noWorkObserved, + "workBefore" in scenario || scenario.name === "deferred-reset" ? undefined : true, + ); + if (scenario.name === "deferred-reset" || scenario.name === "first-request-reset") + assert.equal(terminal.failure.resetAt, resetAt); + if (scenario.name === "newer-reset-during-read") + assert.equal(terminal.failure.resetAt, "2033-05-20T11:06:40.000Z"); + if (scenario.name === "matching-details") + assert.equal(terminal.failure.message, "Detailed provider allowance explanation."); + if ("resetAfter" in scenario) { + yield* Deferred.await(snapshotReceipt); + assert.isFalse( + harness.events.some( (event) => event.type === "turn_item.updated" && event.turnItem.type === "error" && - event.turnItem.failure.resetAt === resetAt, + event.turnItem.failure.resetAt != null, + ), + ); + } + if (scenario.name === "late-reset") { + yield* Deferred.await(resetReceipt); + const item = harness.events.find( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "error" && + event.turnItem.failure.resetAt === resetAt, + ); + assert.isDefined(item); + } + if (scenario.name === "retry" || "willRetry" in scenario) + assert.equal(terminal.retry?.attempt, 1); + if ("expectedCode" in scenario && "expectedMessage" in scenario) { + assert.equal(terminal.failure.code, scenario.expectedCode); + assert.include(terminal.failure.message, scenario.expectedMessage); + assert.equal(terminal.failure.resetAt, null); + if (scenario.expectedCode === "subscription_sharing_unsupported_capability") { + assert.include( + terminal.failure.message, + `Codex instance "${CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID}"`, ); - assert.isDefined(item); - } - if (scenario.name === "retry" || "willRetry" in scenario) - assert.equal(terminal.retry?.attempt, 1); - if ("expectedCode" in scenario && "expectedMessage" in scenario) { - assert.equal(terminal.failure.code, scenario.expectedCode); - assert.include(terminal.failure.message, scenario.expectedMessage); - assert.equal(terminal.failure.resetAt, null); - if (scenario.expectedCode === "subscription_sharing_unsupported_capability") { - assert.include( - terminal.failure.message, - `Codex instance "${CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID}"`, - ); - assert.notInclude(terminal.failure.message, "dummy-sensitive"); - } + assert.notInclude(terminal.failure.message, "dummy-sensitive"); } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -7154,142 +7221,51 @@ describe("CodexAdapterV2 post-settle continuation", () => { ] as const)( "honors completion HTTP status from $notificationStatus to $completionStatus (retry: $willRetry)", ({ notificationStatus, completionStatus, expectedClass, willRetry }) => - Effect.scoped( - Effect.gen(function* () { - const name = `${notificationStatus}-${completionStatus}-${willRetry}`; - const nativeThreadId = `native-exhaustion-status-${name}`; - const nativeTurnId = `turn-exhaustion-status-${name}`; - const message = "Provider stopped this request."; - const additionalDetails = "Detailed notification evidence."; - const transcript = makeCodexReplayTranscript({ - scenario: `codex-exhaustion-status-${name}`, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - { - type: "emit_inbound", - label: "error", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry, - error: { - message, - codexErrorInfo: { - responseTooManyFailedAttempts: { httpStatusCode: notificationStatus }, - }, - additionalDetails, - }, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), - error: { - message, - codexErrorInfo: { - responseTooManyFailedAttempts: { httpStatusCode: completionStatus }, - }, - }, - }, - }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - text: "Continue.", - attemptId: RunAttemptId.make(`attempt-exhaustion-status-${name}`), - }), - ); - yield* harness.firstTerminal; - const terminal = harness.terminalEvents()[0]; - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.equal(terminal.failure.class, expectedClass); - assert.equal(terminal.failure.code, "responseTooManyFailedAttempts"); - assert.equal(terminal.threadDisposition, "reusable"); - const notificationClass = notificationStatus === 429 ? "usage_limit" : "provider_error"; - assert.equal( - terminal.failure.message, - expectedClass === notificationClass ? additionalDetails : message, - ); - if (willRetry) assert.equal(terminal.retry?.attempt, 1); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ), - ); - - // regression: #28032 an unlisted codexErrorInfo dropped the failed turn/completed - it.effect("fails the turn when Codex reports an error info the schema does not list", () => - Effect.scoped( Effect.gen(function* () { - const nativeThreadId = "native-unlisted-error-info"; - const nativeTurnId = "turn-unlisted-error-info"; - const message = - "The 'gpt-5-codex' model is not supported when using Codex with a ChatGPT account."; - const error = { message, codexErrorInfo: "modelNotFound", additionalDetails: null }; - const usage = { - totalTokens: 1, - inputTokens: 1, - cachedInputTokens: 0, - outputTokens: 0, - reasoningOutputTokens: 0, - }; + const name = `${notificationStatus}-${completionStatus}-${willRetry}`; + const nativeThreadId = `native-exhaustion-status-${name}`; + const nativeTurnId = `turn-exhaustion-status-${name}`; + const message = "Provider stopped this request."; + const additionalDetails = "Detailed notification evidence."; const transcript = makeCodexReplayTranscript({ - scenario: "codex-unlisted-error-info", + scenario: `codex-exhaustion-status-${name}`, entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }), - { - type: "emit_inbound", - label: "error", - frame: { - method: "error", - params: { threadId: nativeThreadId, turnId: nativeTurnId, willRetry: false, error }, - }, - }, + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), { type: "emit_inbound", - label: "turn/completed", + label: "error", frame: { - method: "turn/completed", + method: "error", params: { threadId: nativeThreadId, - turn: { ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), error }, + turnId: nativeTurnId, + willRetry, + error: { + message, + codexErrorInfo: { + responseTooManyFailedAttempts: { httpStatusCode: notificationStatus }, + }, + additionalDetails, + }, }, }, }, - // Notifications dispatch in order, so this marks turn/completed as handled. { type: "emit_inbound", - label: "usage", + label: "turn/completed", frame: { - method: "thread/tokenUsage/updated", + method: "turn/completed", params: { threadId: nativeThreadId, - turnId: nativeTurnId, - tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), + error: { + message, + codexErrorInfo: { + responseTooManyFailedAttempts: { httpStatusCode: completionStatus }, + }, + }, + }, }, }, }, @@ -7301,22 +7277,23 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - text: "say hi", - attemptId: RunAttemptId.make("attempt-unlisted-error-info"), + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-exhaustion-status-${name}`), }), ); - yield* harness.until( - () => - harness.terminalEvents().length > 0 || - harness.events.some( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.tokenUsage != null, - ), - ); + yield* harness.firstTerminal; const terminal = harness.terminalEvents()[0]; assert.equal(terminal?.status, "failed"); if (terminal?.status !== "failed") return; - assert.equal(terminal.failure.message, message); + assert.equal(terminal.failure.class, expectedClass); + assert.equal(terminal.failure.code, "responseTooManyFailedAttempts"); + assert.equal(terminal.threadDisposition, "reusable"); + const notificationClass = notificationStatus === 429 ? "usage_limit" : "provider_error"; + assert.equal( + terminal.failure.message, + expectedClass === notificationClass ? additionalDetails : message, + ); + if (willRetry) assert.equal(terminal.retry?.attempt, 1); }).pipe( Effect.provide( Layer.mergeAll( @@ -7327,6 +7304,92 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ), ), + ); + + // regression: #28032 an unlisted codexErrorInfo dropped the failed turn/completed + it.effect("fails the turn when Codex reports an error info the schema does not list", () => + Effect.gen(function* () { + const nativeThreadId = "native-unlisted-error-info"; + const nativeTurnId = "turn-unlisted-error-info"; + const message = + "The 'gpt-5-codex' model is not supported when using Codex with a ChatGPT account."; + const error = { message, codexErrorInfo: "modelNotFound", additionalDetails: null }; + const usage = { + totalTokens: 1, + inputTokens: 1, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + }; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-unlisted-error-info", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }), + { + type: "emit_inbound", + label: "error", + frame: { + method: "error", + params: { threadId: nativeThreadId, turnId: nativeTurnId, willRetry: false, error }, + }, + }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), error }, + }, + }, + }, + // Notifications dispatch in order, so this marks turn/completed as handled. + { + type: "emit_inbound", + label: "usage", + frame: { + method: "thread/tokenUsage/updated", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "say hi", + attemptId: RunAttemptId.make("attempt-unlisted-error-info"), + }), + ); + yield* harness.until( + () => + harness.terminalEvents().length > 0 || + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage != null, + ), + ); + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.message, message); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), ), ); @@ -7391,47 +7454,45 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); it.effect("terminalizes running command items before turn.terminal on failed turns", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(failedMidCommandTranscript); - const now = yield* DateTime.now; + Effect.gen(function* () { + const harness = yield* makeCodexReplayHarness(failedMidCommandTranscript); + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-failed-mid-command"), - text: FAILED_PROMPT, - }), - ); - yield* harness.awaitTerminal(1); - assert.equal(harness.terminalEvents()[0]?.status, "failed"); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-failed-mid-command"), + text: FAILED_PROMPT, + }), + ); + yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "failed"); - const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); - const failedCommandIndex = harness.events.findIndex( - (event, index) => - index < terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "failed", - ); - assert.isAtLeast(failedCommandIndex, 0); - assert.isAbove( - terminalIndex, - failedCommandIndex, - "failed-turn command terminalization must precede turn.terminal", - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), + const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); + const failedCommandIndex = harness.events.findIndex( + (event, index) => + index < terminalIndex && + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "failed", + ); + assert.isAtLeast(failedCommandIndex, 0); + assert.isAbove( + terminalIndex, + failedCommandIndex, + "failed-turn command terminalization must precede turn.terminal", + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.lengthOf(harness.continuationRequests, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, ), ), ), @@ -7532,74 +7593,72 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); it.effect("captures an MCP app's resource and holds the turn open until it lands", () => - Effect.scoped( - Effect.gen(function* () { - const appCaptured = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness(mcpAppTranscript, (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.status === "completed" - ? Deferred.succeed(appCaptured, event.turnItem) - : Effect.void, - ); - const now = yield* DateTime.now; + Effect.gen(function* () { + const appCaptured = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness(mcpAppTranscript, (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.status === "completed" + ? Deferred.succeed(appCaptured, event.turnItem) + : Effect.void, + ); + const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-mcp-app"), - text: MCP_APP_PROMPT, - }), - ); - const item = yield* Deferred.await(appCaptured); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-codex-mcp-app"), + text: MCP_APP_PROMPT, + }), + ); + const item = yield* Deferred.await(appCaptured); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); - const completedRows = harness.events.filter( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.status === "completed", - ); - assert.lengthOf(completedRows, 1); + const completedRows = harness.events.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.status === "completed", + ); + assert.lengthOf(completedRows, 1); - assert.equal(item.type, "dynamic_tool"); - const output = item.type === "dynamic_tool" ? (item.output as Record) : {}; - const reference = readMcpAppReference(output[MCP_APP_OUTPUT_KEY]); - assert.deepEqual( - { ...reference, attachmentId: undefined }, - { - attachmentId: undefined, - server: "weather", - tool: "get_weather", - resourceUri: MCP_APP_RESOURCE, - csp: { connectDomains: ["https://api.weather.test"] }, - }, - ); - assert.deepEqual(output.result, { - content: [{ type: "text", text: "Sunny" }], - structuredContent: { temp: 21 }, - }); + assert.equal(item.type, "dynamic_tool"); + const output = item.type === "dynamic_tool" ? (item.output as Record) : {}; + const reference = readMcpAppReference(output[MCP_APP_OUTPUT_KEY]); + assert.deepEqual( + { ...reference, attachmentId: undefined }, + { + attachmentId: undefined, + server: "weather", + tool: "get_weather", + resourceUri: MCP_APP_RESOURCE, + csp: { connectDomains: ["https://api.weather.test"] }, + }, + ); + assert.deepEqual(output.result, { + content: [{ type: "text", text: "Sunny" }], + structuredContent: { temp: 21 }, + }); - const fileSystem = yield* FileSystem.FileSystem; - const stored = yield* fileSystem.readFileString( - resolveAttachmentPathById({ - attachmentsDir: harness.serverConfig.attachmentsDir, - attachmentId: reference!.attachmentId, - })!, - ); - assert.include(stored, "connect-src https://api.weather.test"); - assert.isBelow(stored.indexOf("Content-Security-Policy"), stored.indexOf("`); + await expect( + ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }), + ).rejects.toThrow(); + expect(await page.locator("body").getAttribute("data-clicked")).toBeNull(); + }); + it("does not retarget a removed ref to a replacement node", async () => { await page.setContent(""); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original"); @@ -577,6 +589,98 @@ describe("server browser drag", () => { process.off("unhandledRejection", onUnhandled); } }); + + it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => { + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage(); + await page.setContent(` +
+
source
+
target
+
+ `); + + await ServerBrowserPage.drag(page, { source: "#source", target: "#target" }); + + const events = (await page.evaluate("window.events")) as Array; + expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]); + expect(events.at(-1)).toBe("mouseup"); + } finally { + await browser.close(); + } + }); +}); + +describe("server browser click", () => { + it("clicks a target the page replaced while it was being scrolled into view", async () => { + let scrolls = 0; + const clicks: Array = []; + const page = { + locator: () => ({ + // Playwright resolves the node once; a page re-rendering it detaches that node. + scrollIntoViewIfNeeded: async () => { + if (scrolls++ === 0) { + throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM"); + } + }, + boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }), + click: async (options: unknown) => { + clicks.push(options); + }, + count: async () => 1, + }), + once: () => {}, + off: () => {}, + } as unknown as Page; + + await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({ + x: 10, + y: 10, + }); + expect(clicks).toHaveLength(1); + }); + + it("retries a replaced target only within the action's timeout", async () => { + vi.useFakeTimers(); + try { + const timeouts: Array = []; + const clicks: Array = []; + const detached = new Error( + "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM", + ); + const page = { + locator: () => ({ + scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => { + timeouts.push(options?.timeout); + vi.advanceTimersByTime(60); + throw detached; + }, + click: async (options: unknown) => { + clicks.push(options); + }, + }), + } as unknown as Page; + + await expect( + ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }), + ).rejects.toBe(detached); + expect(timeouts).toEqual([100, 40]); + expect(clicks).toHaveLength(0); + } finally { + vi.useRealTimers(); + } + }); }); describe("server browser evaluate", () => { diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 0d5ed3d1ff893..3354554f1dd90 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -22,6 +22,7 @@ import { constVoid } from "effect/Function"; import * as Schema from "effect/Schema"; import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; +import * as NodeUtil from "node:util"; import { BrowserControlInterrupted } from "./SessionControl.ts"; const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted); @@ -62,7 +63,7 @@ export const toOperationError = ( if (cause instanceof Error && cause.name === "TimeoutError") { return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: firstLine, + message: withActionabilityReason(firstLine, cause), detail: timeoutMs === undefined ? undefined : { timeoutMs }, }); } @@ -84,6 +85,17 @@ export const toOperationError = ( }); }; +/** Playwright puts why an element was not actionable in its call log, below the first line. */ +const withActionabilityReason = (message: string, cause: Error) => { + // Playwright dims call-log lines with ANSI escapes when colour is on. + const reason = NodeUtil.stripVTControlCharacters(cause.message) + .split("\n") + .map((line) => line.trim()) + .findLast((line) => line.startsWith("- element is ")) + ?.slice(2); + return reason === undefined ? message : `${message} Playwright last saw: ${reason}.`; +}; + const DEFAULT_TIMEOUT_MS = 15_000; const TARGET_COUNT_MS = 250; const MAX_TARGET_CHARS = 200; @@ -147,15 +159,32 @@ export type PointerReporter = ( ) => Promise; const noPointer: PointerReporter = async () => {}; +// Locator.scrollIntoViewIfNeeded resolves its node once and fails when the page replaces it; the +// input actions after it re-resolve, so the scroll does too, within the same timeout. +const DETACHED = /^locator\.scrollIntoViewIfNeeded: Element is not attached to the DOM(?:\n|$)/; + +const scrollIntoView = async (locator: Locator, timeout: number) => { + const deadline = Date.now() + timeout; + for (;;) { + try { + return await locator.scrollIntoViewIfNeeded({ timeout: Math.max(1, deadline - Date.now()) }); + } catch (cause) { + if (!(cause instanceof Error && DETACHED.test(cause.message)) || Date.now() >= deadline) { + throw cause; + } + } + } +}; + const targetPoint = async ( page: Page, locator: Locator | null, input: { readonly x?: number | undefined; readonly y?: number | undefined }, - timeout: number, + timeout: () => number, ) => { if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 }; - await locator.scrollIntoViewIfNeeded({ timeout }); - const box = await locator.boundingBox({ timeout }); + await scrollIntoView(locator, timeout()); + const box = await locator.boundingBox({ timeout: timeout() }); if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; const viewport = page.viewportSize(); return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 }; @@ -694,10 +723,12 @@ export const click = async ( input: PreviewAutomationClickInput, pointer: PointerReporter = noPointer, ): Promise<{ readonly x: number; readonly y: number }> => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); try { - return await clickTarget(page, locator, input, timeout, pointer); + return await clickTarget(page, locator, input, remaining, pointer); } catch (cause) { throw locator === null ? cause : await namedTargetTimeout(locator, input, cause); } @@ -733,10 +764,11 @@ const namedTargetTimeout = async ( : matches === 0 ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; + const message = withActionabilityReason(reason, cause); return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: reason, - detail: { reason }, + message, + detail: { reason: message }, cause, }); }; @@ -745,7 +777,7 @@ const clickTarget = async ( page: Page, locator: Locator | null, input: PreviewAutomationClickInput, - timeout: number, + timeout: () => number, pointer: PointerReporter, ) => { const point = await targetPoint(page, locator, input, timeout); @@ -754,7 +786,7 @@ const clickTarget = async ( const clicked = locator === null ? page.mouse.click(point.x, point.y, options) - : locator.click({ ...options, timeout }); + : locator.click({ ...options, timeout: timeout() }); let onDialog = constVoid; const dialogOpened = new Promise<"dialog">((resolve) => { onDialog = () => resolve("dialog"); @@ -835,7 +867,7 @@ export const hover = async ( ) => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); - await pointer(await targetPoint(page, locator, input, timeout), "move"); + await pointer(await targetPoint(page, locator, input, () => timeout), "move"); if (locator === null) { await page.mouse.move(input.x ?? 0, input.y ?? 0); return; @@ -886,9 +918,10 @@ export const drag = async ( const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const source = targetLocator(page, { locator: input.source })!; const target = targetLocator(page, { locator: input.target })!; - await pointer(await targetPoint(page, source, {}, timeout), "move"); + await pointer(await targetPoint(page, source, {}, () => timeout), "move"); // Observe drag rejection immediately; an unhandled rejection during cursor movement exits the server. - const dragFailure = source.dragTo(target, { timeout }).then( + // Chromium delivers a single move before dragstart; steps give the page mousemoves during the drag. + const dragFailure = source.dragTo(target, { timeout, steps: 5 }).then( () => null, (error: unknown) => ({ error }), ); @@ -1102,7 +1135,8 @@ export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => window.__t3Recorder = { async frame(base64, cssWidth) { if (tooLarge) return false; - const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); + // A per-character atob copy costs ~30 ms on a 3200x1800 frame and throttles recordings. + const bytes = Uint8Array.fromBase64(base64); const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" })); if (tooLarge) { bitmap.close(); return false; } if (!recorder) { diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts index c4a709ed8acc4..c0a9fbc923ff2 100644 --- a/apps/server/src/preview/ServerBrowserStream.test.ts +++ b/apps/server/src/preview/ServerBrowserStream.test.ts @@ -57,6 +57,7 @@ const mutations = [ { type: "navigate", url: "https://example.com" }, { type: "history", delta: -1 }, { type: "reload" }, + { type: "stopLoading" }, { type: "probe", x: 10, y: 10 }, { type: "takeControl" }, { type: "releaseControl" }, @@ -149,7 +150,7 @@ it.effect.each([ }, ]); expect(auth.requests).toEqual([resource]); - }).pipe(Effect.scoped), + }), ); it.effect("sends replies ahead of stale frames and only the newest frame after an ack", () => @@ -221,7 +222,7 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a yield* Effect.promise(() => next.promise); expect(received).toEqual([1, "probe", 4]); expect(released).toEqual([2, 3, 1]); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -264,7 +265,7 @@ it.effect.each([ ); expect(response.status).toBe(testCase.status); expect(attachments).toBe(0); - }).pipe(Effect.scoped), + }), ); it.effect("serves a tab's download only to an authorized session", () => @@ -369,7 +370,7 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco { chooserId: "chooser-1", files: [{ name: "notes.txt", text: "hello" }] }, ]); expect((yield* upload([AuthPreviewOperateScope], "stale")).status).toBe(409); - }).pipe(Effect.scoped), + }), ); const decodeHostSetup = Schema.decodeUnknownEffect(Schema.fromJsonString(PreviewStreamHostSetup)); @@ -430,5 +431,5 @@ it.effect.each([ need, command: "sudo t3 browser setup", }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 0095146a3021f..a44ff15359f35 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -16,6 +16,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as ServerConfig from "../config.ts"; import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts"; const running: ScopeState = { @@ -55,7 +56,14 @@ const withFakeSystemd = ( { oomPolicy = true, stopFails = false, - }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {}, + leftovers = false, + liveOwner = false, + }: { + readonly oomPolicy?: boolean; + readonly stopFails?: boolean; + readonly leftovers?: boolean; + readonly liveOwner?: boolean; + } = {}, ) => Effect.gen(function* () { const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-")); @@ -102,7 +110,12 @@ const withFakeSystemd = ( }), }); const fileSystem = yield* FileSystem.FileSystem; + const { stateDir } = yield* ServerConfig.ServerConfig; + if (leftovers) { + units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" }); + } const scope = yield* make.pipe( + Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }), Effect.provideService(ProcessRunner.ProcessRunner, runner), Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }), @@ -114,7 +127,6 @@ const withFakeSystemd = ( fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options), }), ); - const { stateDir } = yield* ServerConfig.ServerConfig; return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe( Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))), ); @@ -308,27 +320,34 @@ describe("AgentScope service", () => { ), ); - it.effect("stops agents a killed server left before the first launch", () => - withFakeSystemd(({ scope, units, calls, stateDir }) => - Effect.gen(function* () { - units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" }); - const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); - const stops = calls.filter(([, verb]) => verb === "stop"); - expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]); - expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir)); - expect(agent.args).toContain("--property=TimeoutStopSec=10s"); - const terminal = yield* scope.wrap({ - command: "agent", - args: [], - name: "terminal", - survivesRestart: true, - }); - expect(sliceOf(terminal)).toBe("app-t3code-agents.slice"); - expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1); - }), + it.effect("stops agents a killed server left before startup completes", () => + withFakeSystemd( + ({ scope, calls, stateDir }) => + Effect.gen(function* () { + expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]); + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir)); + expect(agent.args).toContain("--property=TimeoutStopSec=10s"); + const terminal = yield* scope.wrap({ + command: "agent", + args: [], + name: "terminal", + survivesRestart: true, + }); + expect(sliceOf(terminal)).toBe("app-t3code-agents.slice"); + expect(stopsOf(calls)).toHaveLength(1); + }), + { leftovers: true }, ), ); + it.effect("leaves the slice to another live server sharing this home", () => + withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), { + leftovers: true, + liveOwner: true, + }), + ); + it.effect("stops leftover processes only in an active agent scope", () => withFakeSystemd(({ scope, units, calls, cgroupRoot }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index b9b6b56acb140..7adc4c453be08 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -17,6 +17,7 @@ import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; const AGENT_SLICE = "app-t3code-agents.slice"; // Owns every agent slice and competes with the server's unit or scope under app.slice. @@ -106,6 +107,7 @@ export const make = Effect.gen(function* () { const path = yield* Path.Path; const hostEnvironment = yield* HostProcess.Environment; const { stateDir } = yield* ServerConfig.ServerConfig; + const { hasOtherLiveOwner } = yield* ProviderProcesses.ProviderProcesses; const ownedSlice = ownedAgentSlice(stateDir); const layerScope = yield* Effect.scope; @@ -130,6 +132,7 @@ export const make = Effect.gen(function* () { const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* ( systemctl: string, ) { + if (hasOtherLiveOwner) return; const shown = yield* run(systemctl, [ "--user", "show", @@ -215,6 +218,10 @@ export const make = Effect.gen(function* () { }), ); + // Layer acquisition is the startup barrier: recovery must not terminalize or + // continue old runs while a previous server's providers can still execute. + yield* systemd; + // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd. const scopeByThread = new Map(); @@ -427,4 +434,7 @@ export const make = Effect.gen(function* () { } satisfies AgentScopeShape; }); -export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer)); +export const layer = Layer.effect(AgentScope, make).pipe( + Layer.provide(ProcessRunner.layer), + Layer.provideMerge(ProviderProcesses.layer), +); diff --git a/apps/server/src/process/providerProcesses.test.ts b/apps/server/src/process/providerProcesses.test.ts new file mode 100644 index 0000000000000..26bad1cec9acc --- /dev/null +++ b/apps/server/src/process/providerProcesses.test.ts @@ -0,0 +1,127 @@ +// @effect-diagnostics nodeBuiltinImport:off -- real processes stand in for servers and CLIs. +import * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import * as ProviderProcesses from "./providerProcesses.ts"; + +// Real child processes stand in for servers and CLIs; only PIDs captured at spawn are signalled. +const ownedProcess = Effect.gen(function* () { + const ready = yield* Deferred.make(); + const exited = yield* Deferred.make(); + const child = yield* Effect.acquireRelease( + Effect.sync(() => { + const child = NodeChildProcess.spawn( + process.execPath, + ["-e", 'process.stdin.resume(); process.send("ready");'], + { stdio: ["pipe", "ignore", "ignore", "ipc"] }, + ); + child.once("message", () => Deferred.doneUnsafe(ready, Effect.void)); + child.once("error", (error) => Deferred.doneUnsafe(ready, Effect.die(error))); + child.once("exit", () => Deferred.doneUnsafe(exited, Effect.void)); + return child; + }), + (child) => + Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))), + ); + yield* Deferred.await(ready); + const pid = child.pid; + assert(pid !== undefined); + const controller = AcpSessionRuntime.makePosixProcessTreeController("linux"); + const identity = controller.identity(pid); + assert(identity !== undefined); + const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + return { + pid, + startTime: `${boot}:${identity.startTime}`, + pgid: 0, + running: () => { + const observed = controller.identity(pid); + return observed !== undefined && !AcpSessionRuntime.posixProcessIsZombie(observed); + }, + stop: Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))), + }; +}); + +describe.runIf(HostProcess.Platform.defaultValue() === "linux")("ProviderProcesses", () => { + it.live("reaps only recorded CLIs of dead servers before startup completes", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const directory = NodePath.join(config.stateDir, "provider-processes"); + NodeFS.mkdirSync(directory, { recursive: true }); + type Identity = { readonly pid: number; readonly startTime: string }; + const record = (owner: Identity, processes: ReadonlyArray) => { + const instanceId = NodeCrypto.randomUUID(); + NodeFS.writeFileSync( + NodePath.join(directory, `${instanceId}.json`), + JSON.stringify({ + version: 1, + instanceId, + hostname: NodeOS.hostname(), + stateDir: config.stateDir, + owner: { pid: owner.pid, startTime: owner.startTime }, + processes: processes.map(({ pid, startTime }) => ({ pid, startTime, pgid: 0 })), + }), + ); + }; + const reused = (identity: Identity) => ({ + ...identity, + startTime: identity.startTime.replace(/:\d+$/, ":1"), + }); + const deadOwner = yield* ownedProcess; + const liveOwner = yield* ownedProcess; + const reusedOwner = yield* ownedProcess; + const liveProvider = yield* ownedProcess; + const reusedProvider = yield* ownedProcess; + const orphan = yield* ownedProcess; + const orphanOfReusedOwner = yield* ownedProcess; + const unrecorded = yield* ownedProcess; + record(liveOwner, [liveProvider]); + record(deadOwner, [reused(reusedProvider)]); + record(deadOwner, [orphan]); + record(reused(reusedOwner), [orphanOfReusedOwner]); + yield* deadOwner.stop; + + const context = yield* Layer.build(ProviderProcesses.layer); + expect(Context.get(context, ProviderProcesses.ProviderProcesses).hasOtherLiveOwner).toBe( + true, + ); + + expect({ + orphan: orphan.running(), + orphanOfReusedOwner: orphanOfReusedOwner.running(), + liveProvider: liveProvider.running(), + reusedProvider: reusedProvider.running(), + reusedOwner: reusedOwner.running(), + unrecorded: unrecorded.running(), + }).toEqual({ + orphan: false, + orphanOfReusedOwner: false, + liveProvider: true, + reusedProvider: true, + reusedOwner: true, + unrecorded: true, + }); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-restart-ownership-" }).pipe( + Layer.provideMerge(NodeServices.layer), + ), + ), + ), + ); +}); diff --git a/apps/server/src/process/providerProcesses.ts b/apps/server/src/process/providerProcesses.ts new file mode 100644 index 0000000000000..4fe9a47637a04 --- /dev/null +++ b/apps/server/src/process/providerProcesses.ts @@ -0,0 +1,140 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the SDK's synchronous spawn callback must record ownership before releasing the child. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import * as ServerConfig from "../config.ts"; + +const ProcessIdentity = Schema.Struct({ + pid: Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: Number.MAX_SAFE_INTEGER })), + startTime: Schema.String, +}); +const OwnershipRecord = Schema.Struct({ + version: Schema.Literal(1), + instanceId: Schema.String, + hostname: Schema.String, + stateDir: Schema.String, + owner: ProcessIdentity, + processes: Schema.Array(Schema.Struct({ ...ProcessIdentity.fields, pgid: Schema.Int })), +}); +const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(OwnershipRecord)); + +// A concurrent exit can remove the record. Incomplete/unknown records never authorize a signal. +const readRecord = (recordPath: string) => { + try { + return decodeRecord(NodeFS.readFileSync(recordPath, "utf8")); + } catch { + return undefined; + } +}; + +export const ProviderProcesses = Context.Reference<{ + readonly register?: (pid: number) => () => void; + readonly hasOtherLiveOwner: boolean; +}>("t3/process/ProviderProcesses", { defaultValue: () => ({ hasOtherLiveOwner: false }) }); + +const make = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return { hasOtherLiveOwner: false }; + const { stateDir } = yield* ServerConfig.ServerConfig; + const directory = NodePath.join(stateDir, "provider-processes"); + const hostname = NodeOS.hostname(); + const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + const controller = AcpSessionRuntime.makePosixProcessTreeController(platform); + const identity = (pid: number) => { + const observed = controller.identity(pid); + if (observed === undefined || AcpSessionRuntime.posixProcessIsZombie(observed)) + return undefined; + return { ...observed, startTime: `${boot}:${observed.startTime}` }; + }; + const matches = (expected: typeof ProcessIdentity.Type) => + identity(expected.pid)?.startTime === expected.startTime; + const kill = (survivor: typeof ProcessIdentity.Type) => { + try { + controller.signalProcess(survivor.pid, "SIGKILL"); + } catch {} + }; + const owner = identity(process.pid); + if (owner === undefined) return yield* Effect.die(new Error("Cannot identify provider owner")); + NodeFS.mkdirSync(directory, { recursive: true }); + + const writeRecord = (processes: (typeof OwnershipRecord.Type)["processes"]) => { + const instanceId = NodeCrypto.randomUUID(); + const recordPath = NodePath.join(directory, `${instanceId}.json`); + const pendingPath = `${recordPath}.pending`; + NodeFS.writeFileSync( + pendingPath, + JSON.stringify({ + version: 1, + instanceId, + hostname, + stateDir, + owner: { pid: owner.pid, startTime: owner.startTime }, + processes, + } satisfies typeof OwnershipRecord.Type), + ); + NodeFS.renameSync(pendingPath, recordPath); + return () => NodeFS.rmSync(recordPath, { force: true }); + }; + // Publish the server identity even before its first provider. Another server + // using this home must not stop the shared systemd slice while we are alive. + const forgetOwner = writeRecord([]); + yield* Effect.addFinalizer(() => Effect.sync(forgetOwner)); + let hasOtherLiveOwner = false; + + // Only immutable per-launch records are shared between server instances. A + // live owner's records belong to that server, even when it uses this home. + for (const file of NodeFS.readdirSync(directory)) { + if (!file.endsWith(".json")) continue; + const recordPath = NodePath.join(directory, file); + const record = readRecord(recordPath); + if (record === undefined) continue; + if (record.hostname !== hostname || record.stateDir !== stateDir) continue; + if (matches(record.owner)) { + if (record.owner.pid !== process.pid) hasOtherLiveOwner = true; + continue; + } + let survived = false; + for (const survivor of record.processes) { + if (survivor.pid === process.pid || !matches(survivor)) continue; + // Never infer ownership from argv, executable names, or group membership. + // As in the ACP controller, starttime blocks reuse between observations. + // Node has no pidfd_send_signal, so the final read-to-signal race remains. + kill(survivor); + for (let attempt = 0; matches(survivor) && !survived; attempt++) { + survived = attempt === 100; + if (!survived) yield* Effect.sleep("10 millis"); + } + } + // Like a failed slice stop, an unkillable CLI must not keep the server down; + // its record stays so the next start retries. + if (survived) { + yield* Effect.logWarning("Could not stop a provider left by a previous server", { file }); + continue; + } + NodeFS.rmSync(recordPath, { force: true }); + } + + return { + hasOtherLiveOwner, + register: (pid: number) => { + const provider = identity(pid); + if (provider === undefined || provider.ppid !== process.pid) { + throw new Error("Cannot identify spawned provider"); + } + // A rename keeps startup from seeing a partial write. The child is gated + // until this returns, so an abrupt death cannot leave an unrecorded CLI. + return writeRecord([{ pid, startTime: provider.startTime, pgid: provider.pgid }]); + }, + }; +}); + +export const layer = Layer.effect(ProviderProcesses, make); diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index b05a0a0504cdd..4378a7fde8470 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -92,6 +92,7 @@ function candidate( { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, ], }, + worktree: null as { path: string; branch: string | null } | null, } satisfies AgentSessionScanner.AgentSessionRecentThread; } @@ -304,6 +305,7 @@ it.effect( ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); unowned.thread.omittedMessageCount = 1; + unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" }; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); const importer = yield* makeImporter([ active, @@ -356,6 +358,8 @@ it.effect( expect(notices).toEqual([]); } expect(records.thread.historyOrigin).toBe("v1_import"); + expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null); + expect(records.thread.branch).toBe(source.worktree?.branch ?? null); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ @@ -364,7 +368,10 @@ it.effect( source.source.provider === "claudeAgent" ? { threadId, resume: source.source.providerSessionId } : { threadId: nativeId(source) }, - runtimePayload: { importedTranscripts: [source.source] }, + runtimePayload: { + cwd: source.worktree?.path ?? "/workspace/project", + importedTranscripts: [source.source], + }, }); } }).pipe(Effect.scoped, Effect.provide(persistence)), diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 9c80ebf1049bf..6200fc11188fb 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -309,7 +309,7 @@ const make = Effect.gen(function* () { thread.source === "claudeAgent" ? { threadId, resume: thread.providerSessionId } : { threadId: nativeThreadId }, - runtimePayload: { cwd: project.workspaceRoot }, + runtimePayload: { cwd: outcome.worktree?.path ?? project.workspaceRoot }, }, { onConflict: "ignore" }, ); @@ -362,8 +362,8 @@ const make = Effect.gen(function* () { modelSelection: { instanceId: thread.providerInstanceId, model }, runtimeMode, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - branch: null, - worktreePath: null, + branch: outcome.worktree?.branch ?? null, + worktreePath: outcome.worktree?.path ?? null, linkedPullRequest: null, branchPullRequest: null, activeProviderThreadId: providerThreadId, diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 82890ca9c8353..6dac5a1b0b6c9 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { describe, expect, it } from "@effect/vitest"; import { AgentSessionImportSource, @@ -174,6 +175,21 @@ const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(fu yield* fileSystem.utimes(input.filePath, seconds, seconds); }); +const writeCompressedTranscript = Effect.fn("AgentSessionScanner.test.writeCompressedTranscript")( + function* (input: { + readonly filePath: string; + readonly contents: string; + readonly mtimeMs: number; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true }); + yield* fileSystem.writeFile(input.filePath, NodeZlib.zstdCompressSync(input.contents)); + const seconds = input.mtimeMs / 1000; + yield* fileSystem.utimes(input.filePath, seconds, seconds); + }, +); + const claudeSessionLine = (cwd: string) => `${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`; @@ -326,6 +342,30 @@ const awaitGateReader = (gatePath: string) => (handle) => Effect.promise(() => handle.close()), ); +/** + * Offers each of `filePaths` to `finished` once its `cat` child has exited. A + * deadline fires for every read still in flight, so a test must wait for the + * unblocked reads before it moves the clock. + */ +const layerReportingProcessRunner = ( + filePaths: ReadonlySet, + finished: Queue.Queue, +) => + Layer.effect( + ProcessRunner.ProcessRunner, + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + return ProcessRunner.ProcessRunner.of({ + run: (input) => { + const filePath = input.args.at(-1) ?? ""; + return filePaths.has(filePath) + ? runner.run(input).pipe(Effect.ensuring(Queue.offer(finished, filePath))) + : runner.run(input); + }, + }); + }), + ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer)); + it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { describe("scan", () => { it.effect("reads Claude project cwds from transcripts, newest first", () => @@ -1064,6 +1104,70 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a checkout's sessions from the linked worktrees the scan counts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repo = yield* makeTempDir("t3code-workspace-repo-"); + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + yield* fileSystem.writeFileString(path.join(repo, ".git", "config"), "[core]\n"); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktreeGitDir, "HEAD"), + "ref: refs/heads/feature\n", + ); + const worktree = path.join(repo, ".claude", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktree, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(worktree, ".git"), + `gitdir: ${worktreeGitDir}\n`, + ); + + for (const [index, [cwd, sessionId]] of [ + [repo, "at-root"], + [worktree, "in-worktree"], + ].entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`), + contents: `${JSON.stringify({ + type: "user", + cwd, + sessionId, + message: { role: "user", content: "Fix the project" }, + })}\n${JSON.stringify({ + type: "assistant", + sessionId, + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + })}\n`, + mtimeMs: nowMs - (index + 1) * 60 * 60 * 1000, + }); + } + + const input = { claudeHomePath, codexHomePath }; + const { candidates } = yield* runScan(input); + expect(candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: repo, threadCount: 2 }, + ]); + const outcomes = yield* runRecentThreadOutcomes({ ...input, workspaceRoot: repo }); + expect( + outcomes.flatMap((outcome) => + outcome._tag === "Importable" + ? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }] + : [], + ), + ).toEqual([ + { sessionId: "at-root", worktree: null }, + { sessionId: "in-worktree", worktree: { path: worktree, branch: "feature" } }, + ]); + }), + ); + it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1220,6 +1324,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: workspace, threadCount: 1 }, + ]); + }), + ); + it.effect("discovers projects whose Codex rollouts are zstd-compressed", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "05", + "03", + "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000b.jsonl.zst", + ), + contents: codexRolloutLine(workspace), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ { path: workspace, threadCount: 1 }, ]); @@ -1228,6 +1358,66 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { + it.effect("imports Codex conversations stored only as zstd-compressed rollouts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "20", + "rollout-2026-08-20T10-00-00-019a5f00-0000-7000-8000-00000000000c.jsonl.zst", + ), + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: "019a5f00-0000-7000-8000-00000000000c", cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + timestamp: "2026-08-20T10:00:00.000Z", + payload: { type: "user_message", message: "Compressed prompt" }, + }), + encodeTranscriptRecord({ + type: "response_item", + timestamp: "2026-08-20T10:01:00.000Z", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Compressed answer" }], + }, + }), + ].join("\n"), + mtimeMs: nowMs - 4 * 24 * 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect( + threads.map((thread) => ({ + id: thread.providerSessionId, + messages: thread.messages.map((message) => message.text), + })), + ).toEqual([ + { + id: "019a5f00-0000-7000-8000-00000000000c", + messages: ["Compressed prompt", "Compressed answer"], + }, + ]); + }), + ); + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -2557,28 +2747,11 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( }); } - // The deadline fires for every read still in flight, so on a slow runner the - // neighbours' `cat` children must have exited before the clock moves. - const neighbourConfigs = new Set( - [repos[0], repos[2]].map((repo) => path.join(repo, ".git", "config")), - ); const finishedNeighbourReads = yield* Queue.unbounded(); - const processRunner = Layer.effect( - ProcessRunner.ProcessRunner, - Effect.gen(function* () { - const runner = yield* ProcessRunner.ProcessRunner; - return ProcessRunner.ProcessRunner.of({ - run: (input) => { - const filePath = input.args.at(-1) ?? ""; - return neighbourConfigs.has(filePath) - ? runner - .run(input) - .pipe(Effect.ensuring(Queue.offer(finishedNeighbourReads, filePath))) - : runner.run(input); - }, - }); - }), - ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer)); + const processRunner = layerReportingProcessRunner( + new Set([repos[0], repos[2]].map((repo) => path.join(repo, ".git", "config"))), + finishedNeighbourReads, + ); for (let attempt = 1; attempt <= 2; attempt++) { const scan = yield* Effect.forkChild( @@ -2687,6 +2860,12 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( }); } + const finishedPointerReads = yield* Queue.unbounded(); + const processRunner = layerReportingProcessRunner( + new Set([path.join(worktree, ".git")]), + finishedPointerReads, + ); + // One scanner across scans: later scans skip the files that blocked. yield* Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; @@ -2695,22 +2874,24 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); const first = yield* Effect.forkChild(scanPaths); // Pointer files are read first, then the commondir files they lead to. - for (const gatePath of [ - path.join(pointerCheckout, ".git"), - path.join(worktreeGitDir, "commondir"), - ]) { - yield* Effect.scoped( - Effect.gen(function* () { - yield* awaitGateReader(gatePath); - yield* TestClock.adjust("2 seconds"); - }), - ); - } + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(pointerCheckout, ".git")); + yield* Queue.take(finishedPointerReads); + yield* TestClock.adjust("2 seconds"); + }), + ); + yield* Effect.scoped( + Effect.gen(function* () { + yield* awaitGateReader(path.join(worktreeGitDir, "commondir")); + yield* TestClock.adjust("2 seconds"); + }), + ); expect(yield* Fiber.join(first)).toEqual([pointerCheckout]); for (let attempt = 2; attempt <= LIBUV_POOL_SIZE + 1; attempt++) { expect(yield* scanPaths, `scan ${attempt}`).toEqual([pointerCheckout]); } - }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath, processRunner }))); // Hangs if the scans left libuv pool threads stuck in open(). yield* fileSystem.readFileString(path.join(worktree, ".git")); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index d9ca41b8f26b1..0de2e84b1f6e3 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1,5 +1,6 @@ import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { AgentSessionImportSource, @@ -17,11 +18,13 @@ import { import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as NodeStream from "@effect/platform-node/NodeStream"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Pull from "effect/Pull"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -177,7 +180,11 @@ const decodeCodexHistoryBase = Schema.decodeUnknownOption( ); // Original rollouts end in their thread ID, rewound ones in `_`. const CODEX_ROLLOUT_ID_PATTERN = - /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl$/i; + /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl(?:\.zst)?$/i; +// Codex zstd-compresses older rollouts; their byte limits and offsets count decompressed bytes. +const COMPRESSED_TRANSCRIPT_SUFFIX = ".jsonl.zst"; +const isCompressedTranscript = (filePath: string) => + filePath.endsWith(COMPRESSED_TRANSCRIPT_SUFFIX); // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged. const CODEX_STATE_DATABASE = "state_5.sqlite"; const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption( @@ -216,6 +223,8 @@ export type AgentSessionRecentThread = readonly _tag: "Importable"; readonly thread: AgentSessionThread; readonly source: AgentSessionImportSource; + /** The root's linked worktree the session ran in, or null when it ran in the root. */ + readonly worktree: { readonly path: string; readonly branch: string | null } | null; } | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource } | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource } @@ -861,6 +870,33 @@ export const make = Effect.gen(function* () { const statOption = (target: string) => fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none)); + const transcriptChunkReader = Effect.fn("AgentSessionScanner.transcriptChunkReader")(function* ( + file: FileSystem.File, + filePath: string, + ) { + if (!isCompressedTranscript(filePath)) return (size: number) => file.readAlloc(size); + const pull = yield* Stream.toPull( + fileSystem + .stream(filePath) + .pipe(NodeStream.pipeThroughSimple(() => NodeZlib.createZstdDecompress())), + ); + let pending: Array = []; + let done = false; + // Untraced: called once per chunk inside the caller's traced read. + return Effect.fnUntraced(function* (size: number) { + while (pending.length === 0) { + if (done) return Option.none(); + const next = yield* pull.pipe(Pull.catchDone(() => Effect.undefined)); + if (next === undefined) done = true; + else pending = [...next]; + } + const chunk = pending.shift(); + if (chunk === undefined) return Option.none(); + if (chunk.byteLength > size) pending.unshift(chunk.subarray(size)); + return Option.some(chunk.subarray(0, size)); + }); + }); + const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* ( target: string, knownStats?: FileSystem.File.Info, @@ -945,19 +981,24 @@ export const make = Effect.gen(function* () { | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } | { readonly _tag: "Worktree"; + readonly gitDir: string; readonly mainCheckout: string | null; readonly git: AgentSessionProjectGit | null; } | { readonly _tag: "NotGit" }; const identities = new Map(); - const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = []; + const repositories: Array<{ + directory: string; + gitDir: string; + worktreeGitDir: string | null; + }> = []; const pointers: Array<{ directory: string; gitPath: string }> = []; for (const directory of directories) { const gitPath = path.join(directory, ".git"); const gitStats = yield* statOption(gitPath); if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" }); else if (gitStats.value.type === "Directory") { - repositories.push({ directory, gitDir: gitPath, linkedWorktree: false }); + repositories.push({ directory, gitDir: gitPath, worktreeGitDir: null }); } else pointers.push({ directory, gitPath }); } @@ -972,7 +1013,7 @@ export const make = Effect.gen(function* () { const gitDir = path.resolve(directory, target); if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) { linkedWorktrees.push({ directory, gitDir }); - } else repositories.push({ directory, gitDir, linkedWorktree: false }); + } else repositories.push({ directory, gitDir, worktreeGitDir: null }); } const commonDirTexts = yield* readGitFiles( @@ -981,19 +1022,19 @@ export const make = Effect.gen(function* () { for (const { directory, gitDir } of linkedWorktrees) { const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim(); if (commonDir.length === 0) { - identities.set(directory, { _tag: "Worktree", mainCheckout: null, git: null }); + identities.set(directory, { _tag: "Worktree", gitDir, mainCheckout: null, git: null }); } else repositories.push({ directory, gitDir: path.resolve(gitDir, commonDir), - linkedWorktree: true, + worktreeGitDir: gitDir, }); } const configTexts = yield* readGitFiles( repositories.map(({ gitDir }) => path.join(gitDir, "config")), ); - for (const { directory, gitDir, linkedWorktree } of repositories) { + for (const { directory, gitDir, worktreeGitDir } of repositories) { const configText = configTexts.get(path.join(gitDir, "config")) ?? ""; const originUrl = parseOriginUrlFromGitConfig(configText); const git: AgentSessionProjectGit = { @@ -1002,9 +1043,10 @@ export const make = Effect.gen(function* () { repository: repositoryPathFromRemoteUrl(originUrl), }; // Bare repositories have no main checkout, so offer their linked worktrees independently. - if (linkedWorktree && !isBareGitConfig(configText)) { + if (worktreeGitDir !== null && !isBareGitConfig(configText)) { identities.set(directory, { _tag: "Worktree", + gitDir: worktreeGitDir, // Only a common dir named .git sits inside its main checkout, and an // unreadable config can't rule out a bare repository. mainCheckout: @@ -1018,6 +1060,61 @@ export const make = Effect.gen(function* () { return identities; }); + /** Maps each directory to the project it counts toward: a linked worktree counts toward its main checkout. */ + const resolveDirectoryProjects = Effect.fn("AgentSessionScanner.resolveDirectoryProjects")( + function* (resolvedDirectories: ReadonlyArray) { + // Stat every directory first so one batch reads all git identities. + const directories = new Map>(); + for (const resolved of resolvedDirectories) { + if (directories.has(resolved)) continue; + directories.set(resolved, yield* projectDirectoryStats(resolved)); + } + const directoryGitIdentities = yield* readGitIdentities( + Array.from(directories).flatMap(([directory, stats]) => + Option.isSome(stats) ? [directory] : [], + ), + ); + const projects = new Map< + string, + { + readonly key: string; + readonly path: string; + readonly git: AgentSessionProjectGit | null; + readonly worktreeGitDir: string | null; + } | null + >(); + for (const [resolved, stats] of directories) { + const gitIdentity = directoryGitIdentities.get(resolved); + if (Option.isNone(stats) || gitIdentity === undefined) { + projects.set(resolved, null); + } else if (gitIdentity._tag === "Worktree") { + const { mainCheckout } = gitIdentity; + const mainStats = + mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); + projects.set( + resolved, + mainCheckout !== null && Option.isSome(mainStats) + ? { + key: yield* directoryIdentity(mainCheckout, mainStats.value), + path: mainCheckout, + git: gitIdentity.git, + worktreeGitDir: gitIdentity.gitDir, + } + : null, + ); + } else { + projects.set(resolved, { + key: yield* directoryIdentity(resolved, stats.value), + path: resolved, + git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, + worktreeGitDir: null, + }); + } + } + return projects; + }, + ); + const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* ( source: AgentSessionSource, transcript: TranscriptCandidate, @@ -1037,11 +1134,15 @@ export const make = Effect.gen(function* () { fileSystem.open(transcript.filePath, { flag: "r" }).pipe( Effect.flatMap((file) => Effect.gen(function* () { + const readChunk = yield* transcriptChunkReader(file, transcript.filePath); + const size = isCompressedTranscript(transcript.filePath) + ? Number.POSITIVE_INFINITY + : transcript.identity.size; const decoder = new TextDecoder(); let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.identity.size); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1073,7 +1174,7 @@ export const make = Effect.gen(function* () { ); budget.operationsRemaining -= 1; budget.bytesRemaining -= readSize; - const next = yield* file.readAlloc(readSize); + const next = yield* readChunk(readSize); if (Option.isNone(next)) { return readLastRecord(); } @@ -1090,7 +1191,7 @@ export const make = Effect.gen(function* () { } } - if (bytesRead < transcript.identity.size) { + if (bytesRead < size) { budget.truncated = true; return null; } @@ -1107,8 +1208,12 @@ export const make = Effect.gen(function* () { source: AgentSessionSource, prefix?: { readonly endByteOffset: number; readonly historyBytes: number }, ) { - const readBytes = prefix?.endByteOffset ?? expected.size; - if (readBytes > expected.size || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; + const compressed = isCompressedTranscript(filePath); + const readBytes = + prefix?.endByteOffset ?? (compressed ? MAX_IMPORTED_TRANSCRIPT_BYTES : expected.size); + if ((!compressed && readBytes > expected.size) || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) { + return null; + } return yield* Effect.scoped( fileSystem.open(filePath, { flag: "r" }).pipe( @@ -1117,6 +1222,7 @@ export const make = Effect.gen(function* () { if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) { return null; } + const readChunk = yield* transcriptChunkReader(file, filePath); const records: Array = []; const claudeHistory = createClaudeHistoryWindow(); let cwd = Option.none(); @@ -1177,10 +1283,12 @@ export const make = Effect.gen(function* () { }; while (bytesRead < readBytes) { - const next = yield* file.readAlloc( + const next = yield* readChunk( Math.min(TRANSCRIPT_PREFIX_BYTES, readBytes - bytesRead), ); if (Option.isNone(next)) { + // A compressed rollout's decompressed length is only known at its end. + if (compressed && prefix === undefined) break; return null; } @@ -1398,7 +1506,12 @@ export const make = Effect.gen(function* () { } const directory = path.join(sessionsDir, year, month, day); for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) { - if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue; + if ( + !entry.startsWith("rollout-") || + !(entry.endsWith(".jsonl") || isCompressedTranscript(entry)) + ) { + continue; + } if (operationsRemaining <= 0) { truncated = true; break; @@ -1719,64 +1832,18 @@ export const make = Effect.gen(function* () { git: AgentSessionProjectGit | null; } >(); - // Resolve every candidate directory first so one batch reads all git identities. - const directories = new Map>(); - for (const candidate of raw) { - const expanded = expandHomePath(candidate.cwd.trim(), homeDir); - if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - if (directories.has(resolved)) continue; - directories.set(resolved, yield* projectDirectoryStats(resolved)); - } - const directoryGitIdentities = yield* readGitIdentities( - Array.from(directories).flatMap(([directory, stats]) => - Option.isSome(stats) ? [directory] : [], - ), + const directoryProjects = yield* resolveDirectoryProjects( + raw.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }), ); - const directoryProjects = new Map< - string, - { - readonly key: string; - readonly path: string; - readonly git: AgentSessionProjectGit | null; - } | null - >(); - for (const candidate of raw) { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - const stats = directories.get(resolved); - if (stats === undefined || Option.isNone(stats)) continue; - let project = directoryProjects.get(resolved); - if (project === undefined) { - const gitIdentity = directoryGitIdentities.get(resolved); - if (gitIdentity === undefined) { - project = null; - } else if (gitIdentity._tag === "Worktree") { - // A linked worktree's sessions count toward its main checkout's project. - const { mainCheckout } = gitIdentity; - const mainStats = - mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); - project = - mainCheckout !== null && Option.isSome(mainStats) - ? { - key: yield* directoryIdentity(mainCheckout, mainStats.value), - path: mainCheckout, - git: gitIdentity.git, - } - : null; - } else { - project = { - key: yield* directoryIdentity(resolved, stats.value), - path: resolved, - git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, - }; - } - directoryProjects.set(resolved, project); - } - if (project === null) continue; + const project = directoryProjects.get(path.resolve(expanded)); + if (project === undefined || project === null) continue; const existing = merged.get(project.key); if (!existing) { @@ -1866,6 +1933,45 @@ export const make = Effect.gen(function* () { } const { candidates } = cachedCandidates; + // The scan counts a linked worktree's sessions toward its main checkout, so import them with it. + const candidateDirectories = candidates.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }); + const directoryProjects = yield* resolveDirectoryProjects(candidateDirectories); + const belongsToRoot = Effect.fn("AgentSessionScanner.belongsToRoot")(function* ( + resolved: string, + ) { + if ((yield* directoryIdentity(resolved)) === rootIdentity) return true; + if (!directoryProjects.has(resolved)) { + const project = (yield* resolveDirectoryProjects([resolved])).get(resolved) ?? null; + directoryProjects.set(resolved, project); + } + return directoryProjects.get(resolved)?.key === rootIdentity; + }); + const worktreesByDirectory = new Map(); + const rootWorktree = Effect.fn("AgentSessionScanner.rootWorktree")(function* ( + resolved: string, + ) { + const known = worktreesByDirectory.get(resolved); + if (known !== undefined) return known; + const gitDir = + (yield* directoryIdentity(resolved)) === rootIdentity + ? null + : (directoryProjects.get(resolved)?.worktreeGitDir ?? null); + let worktree: { path: string; branch: string | null } | null = null; + if (gitDir !== null) { + const headPath = path.join(gitDir, "HEAD"); + const head = (yield* readGitFiles([headPath])).get(headPath) ?? ""; + worktree = { + path: resolved, + branch: /^ref: refs\/heads\/(.+)$/.exec(head.trim())?.[1] ?? null, + }; + } + worktreesByDirectory.set(resolved, worktree); + return worktree; + }); + const eligibleTranscripts: Array<{ readonly candidate: RawCandidate; readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number }; @@ -1874,7 +1980,7 @@ export const make = Effect.gen(function* () { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; const resolved = path.resolve(expanded); - if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue; + if (!(yield* belongsToRoot(resolved))) continue; for (const transcript of candidate.transcripts) { if ( @@ -2005,12 +2111,10 @@ export const make = Effect.gen(function* () { projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), homeDir, ); - if ( - !path.isAbsolute(expandedCwd) || - (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity - ) { + if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { return Option.some({ _tag: "Skipped" }); } + const worktree = yield* rootWorktree(path.resolve(expandedCwd)); const inheritedRecords = candidate.source === "codex" @@ -2024,7 +2128,12 @@ export const make = Effect.gen(function* () { { source: candidate.source, providerInstanceId: candidate.providerInstanceId, - fallbackSessionId: path.basename(transcript.filePath, ".jsonl"), + fallbackSessionId: path.basename( + transcript.filePath, + isCompressedTranscript(transcript.filePath) + ? COMPRESSED_TRANSCRIPT_SUFFIX + : ".jsonl", + ), lastActiveAtMs: transcript.mtimeMs, }, inheritedRecords === null @@ -2061,6 +2170,7 @@ export const make = Effect.gen(function* () { thread: savedTitle === undefined ? parsedThread : { ...parsedThread, title: savedTitle }, source, + worktree, }); }).pipe(importReadLock.withPermits(1)), ), diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index fd3f3fde87c8c..4377caf55c524 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -344,6 +344,46 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect("follows an OWNER/REPO mark only to a remote that fetches that repository", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-gh-parent-test-", + }); + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const resolveFresh = () => resolver.resolve(cwd, { refresh: true }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "fork", "https://github.com/julius/t3code-fork.git"]); + yield* git(cwd, ["remote", "add", "main", "https://github.com/T3Tools/t3code.git"]); + yield* git(cwd, ["remote", "add", "upstream", "https://github.com/other/t3code.git"]); + yield* git(cwd, ["config", "remote.fork.gh-resolved", "t3tools/t3code"]); + const parent = yield* resolveFresh(); + expect(parent?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(parent?.locator).toEqual({ + source: "git-remote", + remoteName: "main", + remoteUrl: "https://github.com/T3Tools/t3code.git", + }); + + // No remote fetches the marked repository, and several marks leave gh's choice unknown. + yield* git(cwd, ["config", "remote.fork.gh-resolved", "someone/else"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("upstream"); + yield* git(cwd, ["config", "remote.fork.gh-resolved", "base"]); + yield* git(cwd, ["config", "remote.main.gh-resolved", "base"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("upstream"); + + // The same path on another HTTPS port is a different server. + yield* git(cwd, ["config", "--unset", "remote.fork.gh-resolved"]); + yield* git(cwd, ["config", "--unset", "remote.main.gh-resolved"]); + yield* git(cwd, ["remote", "add", "backup", "https://ghe.example.com:9443/acme/web.git"]); + yield* git(cwd, ["remote", "add", "ghe-fork", "https://ghe.example.com:8443/me/web.git"]); + yield* git(cwd, ["remote", "add", "ghe-parent", "https://ghe.example.com:8443/acme/web.git"]); + yield* git(cwd, ["config", "remote.ghe-fork.gh-resolved", "acme/web"]); + expect((yield* resolveFresh())?.locator.remoteName).toBe("ghe-parent"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("reads the project's gh default when the server inherited GIT_DIR", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index c3367ac460b46..ebd63a957d5b5 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -1,5 +1,7 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; +import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; +import { normalizeGitRemoteUrl } from "@t3tools/shared/git"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -69,21 +71,44 @@ function parseRemoteFetchUrls(stdout: string): Map { return remotes; } -// `gh repo set-default` marks the chosen remote with `remote..gh-resolved base`. -function parseGhDefaultRemoteName(stdout: string): string | null { - const marked = stdout - .split("\n") - .map((line) => /^remote\.(.+)\.gh-resolved\s+base$/.exec(line.trim())?.[1]) - .filter((name): name is string => name !== undefined); - return marked.length === 1 ? marked[0]! : null; +// `gh repo set-default` marks one remote with `base`, or with OWNER/REPO when it picked a +// parent repository. gh reads PRs from that repository, so the identity follows the mark when +// a remote fetches it. The locator must name a real remote: review checkouts fetch through it. +function pickMarkedRemote( + remotes: ReadonlyMap, + resolved: string, +): { readonly remoteName: string; readonly remoteUrl: string } | null { + const marks = resolved.split("\n").flatMap((line) => { + const match = /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()); + const remoteUrl = match?.[1] === undefined ? undefined : remotes.get(match[1]); + return match?.[1] && match[2] && remoteUrl + ? [{ remoteName: match[1], remoteUrl, value: match[2] }] + : []; + }); + // gh's choice is ambiguous with several marks; GitHubSourceControlProvider ignores them too. + const [mark, ...others] = marks; + if (!mark || others.length > 0) return null; + if (mark.value === "base") return { remoteName: mark.remoteName, remoteUrl: mark.remoteUrl }; + // Compare hosts with HTTP ports kept: one hostname can serve separate forges on two ports. + const host = parseGitRemoteHost(mark.remoteUrl)?.host; + const markedPath = mark.value.toLowerCase(); + const [remoteName, remoteUrl] = + [...remotes.entries()].find( + ([, url]) => + parseGitRemoteHost(url)?.host === host && + normalizeGitRemoteUrl(url).split("/").slice(1).join("/") === markedPath, + ) ?? []; + return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; } function pickPrimaryRemote( remotes: ReadonlyMap, - ghDefaultRemoteName: string | null, + resolved: string, ): { readonly remoteName: string; readonly remoteUrl: string } | null { - for (const preferredRemoteName of [ghDefaultRemoteName, "upstream", "origin"]) { - if (preferredRemoteName === null) continue; + const marked = pickMarkedRemote(remotes, resolved); + if (marked) return marked; + + for (const preferredRemoteName of ["upstream", "origin"] as const) { const remoteUrl = remotes.get(preferredRemoteName); if (remoteUrl) { return { remoteName: preferredRemoteName, remoteUrl }; @@ -242,40 +267,30 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( ): Effect.fn.Return { const processRunner = yield* ProcessRunner.ProcessRunner; const env = gitEnv(yield* HostProcess.Platform); - const remoteResult = yield* processRunner - .run({ - command: "git", - args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"], - env, - timeoutBehavior: "timedOutResult", - }) - .pipe(Effect.option); + const runGit = (args: ReadonlyArray) => + processRunner + .run({ + command: "git", + args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args], + env, + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + const [remoteResult, resolvedResult] = yield* Effect.all( + [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])], + { concurrency: "unbounded" }, + ); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { return null; } - const ghResolvedResult = yield* processRunner - .run({ - command: "git", - args: [ - "-C", - cacheKey.rootPath, - ...(cacheKey.isBare ? ["--git-dir=."] : []), - "config", - "--get-regexp", - "^remote\\..*\\.gh-resolved$", - ], - env, - timeoutBehavior: "timedOutResult", - }) - .pipe(Effect.option); - const ghDefaultRemoteName = - ghResolvedResult._tag === "Some" && ghResolvedResult.value.code === 0 - ? parseGhDefaultRemoteName(ghResolvedResult.value.stdout) - : null; - const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); - const remote = pickPrimaryRemote(remotes, ghDefaultRemoteName); + // Exits 1 when no remote has a mark. + const resolved = + resolvedResult._tag === "Some" && resolvedResult.value.code === 0 + ? resolvedResult.value.stdout + : ""; + const remote = pickPrimaryRemote(remotes, resolved); return remote ? buildRepositoryIdentity({ ...remote, diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 3b7b2b42f2b74..30915b31d474f 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -410,7 +410,6 @@ describe("ACP Registry probe", () => { }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - Effect.scoped, ); }); diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 791ed748de2ef..a676273827859 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -291,561 +291,519 @@ describe("Antigravity model catalog", () => { it.layer(layerTest)("Antigravity provider snapshots", (it) => { it.effect("does not probe or run helper safety checks while disabled", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ enabled: false }); - const snapshot = yield* harness.provider.snapshot.refresh; - expect(snapshot).toMatchObject({ - enabled: false, + Effect.gen(function* () { + const harness = yield* makeHarness({ enabled: false }); + const snapshot = yield* harness.provider.snapshot.refresh; + expect(snapshot).toMatchObject({ + enabled: false, + installed: false, + status: "disabled", + auth: { status: "unknown" }, + models: [], + setup: { canAuthenticate: true, canInstall: true }, + showInteractionModeToggle: false, + supportsConversationRollback: false, + supportsTextGeneration: false, + }); + expect(yield* Ref.get(harness.probeCalls)).toBe(0); + expect(yield* Ref.get(harness.safetyCalls)).toBe(0); + }), + ); + + it.effect("treats initialize as installation proof, not account or model discovery", () => + Effect.gen(function* () { + for (const auth of [ + undefined, + { type: "oauth-personal", label: "Google account" }, + { type: "oauth-business", label: "Gemini Enterprise" }, + { type: "gemini-api-key", label: "Gemini API key" }, + { type: "agent-platform", label: "Agent Platform" }, + ]) { + const harness = yield* makeHarness(auth ? { auth } : {}); + expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ installed: false, - status: "disabled", + status: "warning", auth: { status: "unknown" }, models: [], - setup: { canAuthenticate: true, canInstall: true }, - showInteractionModeToggle: false, - supportsConversationRollback: false, - supportsTextGeneration: false, }); - expect(yield* Ref.get(harness.probeCalls)).toBe(0); - expect(yield* Ref.get(harness.safetyCalls)).toBe(0); - }), - ), - ); - - it.effect("treats initialize as installation proof, not account or model discovery", () => - Effect.scoped( - Effect.gen(function* () { - for (const auth of [ - undefined, - { type: "oauth-personal", label: "Google account" }, - { type: "oauth-business", label: "Gemini Enterprise" }, - { type: "gemini-api-key", label: "Gemini API key" }, - { type: "agent-platform", label: "Agent Platform" }, - ]) { - const harness = yield* makeHarness(auth ? { auth } : {}); - expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ - installed: false, - status: "warning", - auth: { status: "unknown" }, - models: [], - }); - yield* harness.initialize; - const snapshot = yield* harness.provider.snapshot.getSnapshot; - expect(snapshot).toMatchObject({ - installed: true, - status: "warning", - version: "agy_acp_server_20260818_01_RC01", - auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) }, - message: - auth?.type === "gemini-api-key" || auth?.type === "agent-platform" - ? `Antigravity is installed. Connect with ${auth.label} to load models.` - : "Antigravity is installed. Google account access is not checked yet.", - models: [], - }); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - } - }), - ), + yield* harness.initialize; + const snapshot = yield* harness.provider.snapshot.getSnapshot; + expect(snapshot).toMatchObject({ + installed: true, + status: "warning", + version: "agy_acp_server_20260818_01_RC01", + auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) }, + message: + auth?.type === "gemini-api-key" || auth?.type === "agent-platform" + ? `Antigravity is installed. Connect with ${auth.label} to load models.` + : "Antigravity is installed. Google account access is not checked yet.", + models: [], + }); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + } + }), ); it.effect("does not offer Auto, so Auto threads fall back to Supervised", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - // Antigravity has no automatic review; the shared ACP policy would approve every request. - expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([ - "approval-required", - "auto-accept-edits", - "full-access", - ]); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + // Antigravity has no automatic review; the shared ACP policy would approve every request. + expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([ + "approval-required", + "auto-accept-edits", + "full-access", + ]); + }), ); it.effect("publishes session metadata and native commands without another health probe", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const nextReady = yield* Stream.toPull( - harness.provider.snapshot.streamChanges.pipe( - Stream.filter( - (snapshot) => - snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0, - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const nextReady = yield* Stream.toPull( + harness.provider.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0, ), - ); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const [snapshot] = yield* nextReady; - expect(snapshot).toMatchObject({ - status: "ready", - auth: { status: "authenticated", type: "oauth-personal" }, - supportsTextGeneration: true, - }); - expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual( - expectedCommands, - ); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - }), - ), + ), + ); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const [snapshot] = yield* nextReady; + expect(snapshot).toMatchObject({ + status: "ready", + auth: { status: "authenticated", type: "oauth-personal" }, + supportsTextGeneration: true, + }); + expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual( + expectedCommands, + ); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + }), ); it.effect("clears all account metadata on sign-out and authentication failure", () => - Effect.scoped( - Effect.gen(function* () { - const auth = { type: "gemini-api-key", label: "Gemini API key" }; - const harness = yield* makeHarness({ auth }); - yield* harness.initialize; - for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) { - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* clear; - expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ - installed: true, - status: "warning", - auth: { status: "unauthenticated", type: auth.type, label: auth.label }, - message: "Connect with Gemini API key to use Antigravity and load models.", - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportsTextGeneration: false, - }); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* harness.provider.onConfigOptionsUpdated([modelConfig]); - expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]); - expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); - } - const refreshed = yield* harness.provider.snapshot.refresh; - expect(refreshed.auth).toEqual({ - status: "unauthenticated", - type: auth.type, - label: auth.label, - }); - expect(refreshed.message).toBe( - "Connect with Gemini API key to use Antigravity and load models.", - ); - expect(refreshed.supportsTextGeneration).toBe(false); - }), - ), - ); - - it.effect("replaces live model choices and accepts an empty catalog", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; + Effect.gen(function* () { + const auth = { type: "gemini-api-key", label: "Gemini API key" }; + const harness = yield* makeHarness({ auth }); + yield* harness.initialize; + for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) { yield* harness.provider.onSessionStarted(started, "/workspace"); yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const before = yield* harness.provider.snapshot.getSnapshot; - const configOptions = [ - { - ...modelConfig, - currentValue: "gemini-3.8-flash-high", - options: modelOptions.slice(0, 3), - }, - ]; - const nextSnapshot = yield* Stream.toPull( - harness.provider.snapshot.streamChanges.pipe( - Stream.filter((snapshot) => snapshot.models.length === 3), - ), - ); - yield* harness.provider.onConfigOptionsUpdated(configOptions); - expect((yield* nextSnapshot)[0]).toMatchObject({ - models: buildAntigravityModelsFromSession({ configOptions }), - auth: before.auth, - workspaceSnapshots: before.workspaceSnapshots, - slashCommands: expectedCommands, + yield* clear; + expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ + installed: true, + status: "warning", + auth: { status: "unauthenticated", type: auth.type, label: auth.label }, + message: "Connect with Gemini API key to use Antigravity and load models.", + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportsTextGeneration: false, }); - yield* harness.provider.onConfigOptionsUpdated([]); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + yield* harness.provider.onConfigOptionsUpdated([modelConfig]); + expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]); expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); - }), - ), + } + const refreshed = yield* harness.provider.snapshot.refresh; + expect(refreshed.auth).toEqual({ + status: "unauthenticated", + type: auth.type, + label: auth.label, + }); + expect(refreshed.message).toBe( + "Connect with Gemini API key to use Antigravity and load models.", + ); + expect(refreshed.supportsTextGeneration).toBe(false); + }), + ); + + it.effect("replaces live model choices and accepts an empty catalog", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const before = yield* harness.provider.snapshot.getSnapshot; + const configOptions = [ + { + ...modelConfig, + currentValue: "gemini-3.8-flash-high", + options: modelOptions.slice(0, 3), + }, + ]; + const nextSnapshot = yield* Stream.toPull( + harness.provider.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.length === 3), + ), + ); + yield* harness.provider.onConfigOptionsUpdated(configOptions); + expect((yield* nextSnapshot)[0]).toMatchObject({ + models: buildAntigravityModelsFromSession({ configOptions }), + auth: before.auth, + workspaceSnapshots: before.workspaceSnapshots, + slashCommands: expectedCommands, + }); + yield* harness.provider.onConfigOptionsUpdated([]); + expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]); + }), ); it.effect("does not guess a version before a custom launcher's first handshake", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* Deferred.succeed(harness.initialProbe, { - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, - }); - yield* harness.initialUpdate; - expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull(); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Deferred.succeed(harness.initialProbe, { + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, + }); + yield* harness.initialUpdate; + expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull(); + }), ); it.effect("does not replace a handshake version with an unknown custom-launcher probe", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted({ - ...started, - initializeResult: { - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" }, - }, - }); - yield* Ref.set( - harness.probe, - Effect.succeed({ - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, - }), - ); - expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0"); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted({ + ...started, + initializeResult: { + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" }, + }, + }); + yield* Ref.set( + harness.probe, + Effect.succeed({ + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "unknown" }, + }), + ); + expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0"); + }), ); it.effect("replaces one account's catalog instead of combining accounts", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - yield* harness.provider.onSignedOut; - yield* harness.provider.onSessionStarted({ - ...started, - sessionSetupResult: { - sessionId: "new-account-session", - configOptions: [ - { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] }, - ], - }, - }); - expect( - (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug), - ).toEqual(["gemini-pro-agent"]); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + yield* harness.provider.onSignedOut; + yield* harness.provider.onSessionStarted({ + ...started, + sessionSetupResult: { + sessionId: "new-account-session", + configOptions: [ + { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] }, + ], + }, + }); + expect( + (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug), + ).toEqual(["gemini-pro-agent"]); + }), ); it.effect("retains known account metadata when a local health check fails", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + yield* Ref.set( + harness.probe, + Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")), + ); + const snapshot = yield* harness.provider.snapshot.refresh; + expect(snapshot).toMatchObject({ + installed: true, + status: "error", + auth: { status: "authenticated" }, + }); + expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace"); + }), + ); + + it.effect("distinguishes missing executables from a failed installed executable", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const failures = [ + { + error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }), + installed: false, + }, + { + error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }), + installed: true, + }, + { + error: new ProviderSetupError({ + instanceId, + operation: "resolve", + detail: "Antigravity is not installed.", + }), + installed: false, + }, + ]; + for (const { error, installed } of failures) { yield* harness.provider.onSessionStarted(started, "/workspace"); yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* Ref.set( - harness.probe, - Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")), - ); + yield* Ref.set(harness.probe, Effect.fail(error)); const snapshot = yield* harness.provider.snapshot.refresh; expect(snapshot).toMatchObject({ - installed: true, + installed, status: "error", auth: { status: "authenticated" }, }); - expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult)); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace"); - }), - ), - ); - - it.effect("distinguishes missing executables from a failed installed executable", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const failures = [ - { - error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }), - installed: false, - }, - { - error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }), - installed: true, - }, - { - error: new ProviderSetupError({ - instanceId, - operation: "resolve", - detail: "Antigravity is not installed.", - }), - installed: false, - }, - ]; - for (const { error, installed } of failures) { - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - yield* Ref.set(harness.probe, Effect.fail(error)); - const snapshot = yield* harness.provider.snapshot.refresh; - expect(snapshot).toMatchObject({ - installed, - status: "error", - auth: { status: "authenticated" }, - }); - expect(snapshot.models).toHaveLength(installed ? 11 : 0); - expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0); - expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0); - expect(snapshot.supportsTextGeneration).toBe(installed); - } - }), - ), + expect(snapshot.models).toHaveLength(installed ? 11 : 0); + expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0); + expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0); + expect(snapshot.supportsTextGeneration).toBe(installed); + } + }), ); it.effect("does not let an old health result restore a signed-out account", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - const releaseProbe = yield* Deferred.make(); - const probeEntered = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Deferred.succeed(probeEntered, undefined).pipe( - Effect.andThen(Deferred.await(releaseProbe)), - ), - ); - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(probeEntered); - yield* harness.provider.onSignedOut; - yield* Deferred.succeed(releaseProbe, initializeResult); - const snapshot = yield* Fiber.join(refresh); - expect(snapshot).toMatchObject({ - auth: { status: "unauthenticated" }, - models: [], - supportsTextGeneration: false, - }); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + const releaseProbe = yield* Deferred.make(); + const probeEntered = yield* Deferred.make(); + yield* Ref.set( + harness.probe, + Deferred.succeed(probeEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseProbe)), + ), + ); + const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); + yield* Deferred.await(probeEntered); + yield* harness.provider.onSignedOut; + yield* Deferred.succeed(releaseProbe, initializeResult); + const snapshot = yield* Fiber.join(refresh); + expect(snapshot).toMatchObject({ + auth: { status: "unauthenticated" }, + models: [], + supportsTextGeneration: false, + }); + }), ); it.effect("exposes helper support only when the supplied safety check allows it", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ safe: false }); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false); - yield* Ref.set(harness.safety, Effect.succeed(true)); - yield* harness.provider.snapshot.refresh; - expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness({ safe: false }); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false); + yield* Ref.set(harness.safety, Effect.succeed(true)); + yield* harness.provider.snapshot.refresh; + expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true); + }), ); it.effect("keeps discovered workspace skills through session and command updates", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const skills = [ - { - name: "deploy", - description: "Ship it", - path: "/workspace/.agent/skills/deploy", - enabled: true, - }, - ]; - const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills); - expect(discovered.skills).toEqual(skills); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onAvailableCommands(commands, "/workspace"); - const after = yield* harness.provider.snapshot.getSnapshot; - expect( - after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills, - ).toEqual(skills); - expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills); - - const rescanned = [ - ...skills, - { name: "review", path: "/workspace/.agent/skills/review", enabled: true }, - ]; - yield* harness.provider.snapshotForCwd("/workspace", rescanned); - yield* harness.provider.onSessionStarted(started, "/workspace"); - expect( - (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find( - (entry) => entry.cwd === "/workspace", - )?.skills, - ).toEqual(rescanned); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + const skills = [ + { + name: "deploy", + description: "Ship it", + path: "/workspace/.agent/skills/deploy", + enabled: true, + }, + ]; + const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills); + expect(discovered.skills).toEqual(skills); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const after = yield* harness.provider.snapshot.getSnapshot; + expect(after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills).toEqual( + skills, + ); + expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills); + + const rescanned = [ + ...skills, + { name: "review", path: "/workspace/.agent/skills/review", enabled: true }, + ]; + yield* harness.provider.snapshotForCwd("/workspace", rescanned); + yield* harness.provider.onSessionStarted(started, "/workspace"); + expect( + (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find( + (entry) => entry.cwd === "/workspace", + )?.skills, + ).toEqual(rescanned); + }), ); it.effect("bounds workspace metadata without starting sessions for workspace lookup", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - for (let index = 0; index < 35; index++) { - yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`); - } - const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34"); - expect(snapshot.workspaceSnapshots).toHaveLength(32); - expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3"); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect(yield* Ref.get(harness.probeCalls)).toBe(1); - }), - ), + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.initialize; + yield* harness.provider.onSessionStarted(started); + for (let index = 0; index < 35; index++) { + yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`); + } + const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34"); + expect(snapshot.workspaceSnapshots).toHaveLength(32); + expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3"); + expect(snapshot.slashCommands).toEqual(expectedCommands); + expect(yield* Ref.get(harness.probeCalls)).toBe(1); + }), ); it.effect( "publishes limits, retains a successful read on failure, and clears them on sign-out", () => - Effect.scoped( - Effect.gen(function* () { - const limits: ServerProviderUsageLimits = { - checkedAt: "2026-10-09T12:00:00.000Z", - windows: [ - { - id: "3p-weekly", - kind: "weekly", - label: "Claude & GPT (shared) · Weekly", - usedPercent: 75, - }, - ], - }; - const usage = yield* Ref.make(limits); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - expect((yield* published)?.usageLimits).toEqual(limits); - // The second health check is the one the failed background read triggers. - const checks = yield* Ref.make(0); - const failedReadApplied = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Ref.updateAndGet(checks, (count) => count + 1).pipe( - Effect.tap((count) => - count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void, - ), - Effect.as(initializeResult), - ), - ); - yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [], - unavailable: { reason: "probeFailed" }, - }); - yield* harness.provider.snapshot.refresh; - yield* Deferred.await(failedReadApplied); - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits); - yield* harness.provider.onSignedOut; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); - yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:02:00.000Z", - windows: [], - unavailable: { reason: "unsupported" }, - }); - const unsupported = yield* harness.nextPublish( - (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported", - ); - yield* harness.provider.snapshot.refresh; - expect((yield* unsupported)?.usageLimits?.windows).toEqual([]); - }), - ), - ); - - it.effect("a quota read finishing after sign-out cannot restore account limits", () => - Effect.scoped( Effect.gen(function* () { - const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); - const usage = yield* Ref.make>( - Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }), - ); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + const limits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [ + { + id: "3p-weekly", + kind: "weekly", + label: "Claude & GPT (shared) · Weekly", + usedPercent: 75, + }, + ], + }; + const usage = yield* Ref.make(limits); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); yield* harness.initialize; - yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + expect((yield* published)?.usageLimits).toEqual(limits); + // The second health check is the one the failed background read triggers. + const checks = yield* Ref.make(0); + const failedReadApplied = yield* Deferred.make(); yield* Ref.set( - usage, - Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))), + harness.probe, + Ref.updateAndGet(checks, (count) => count + 1).pipe( + Effect.tap((count) => + count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void, + ), + Effect.as(initializeResult), + ), ); - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(readStarted); - yield* harness.provider.onSignedOut; - yield* Deferred.succeed(readResult, { + yield* Ref.set(usage, { checkedAt: "2026-10-09T12:01:00.000Z", - windows: [ - { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }, - ], + windows: [], + unavailable: { reason: "probeFailed" }, }); - yield* Fiber.join(refresh); + yield* harness.provider.snapshot.refresh; + yield* Deferred.await(failedReadApplied); + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits); + yield* harness.provider.onSignedOut; expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + yield* Ref.set(usage, { + checkedAt: "2026-10-09T12:02:00.000Z", + windows: [], + unavailable: { reason: "unsupported" }, + }); + const unsupported = yield* harness.nextPublish( + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported", + ); + yield* harness.provider.snapshot.refresh; + expect((yield* unsupported)?.usageLimits?.windows).toEqual([]); }), - ), + ); + + it.effect("a quota read finishing after sign-out cannot restore account limits", () => + Effect.gen(function* () { + const readStarted = yield* Deferred.make(); + const readResult = yield* Deferred.make(); + const usage = yield* Ref.make>( + Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }), + ); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + yield* harness.initialize; + yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + yield* Ref.set( + usage, + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))), + ); + const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + yield* harness.provider.onSignedOut; + yield* Deferred.succeed(readResult, { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + }); + yield* Fiber.join(refresh); + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + }), ); it.effect("reports ready and starts sessions while one shared quota read is pending", () => - Effect.scoped( - Effect.gen(function* () { - const reads = yield* Ref.make(0); - const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); - const harness = yield* makeHarness({ - probeUsage: Ref.update(reads, (count) => count + 1).pipe( - Effect.andThen(Deferred.succeed(readStarted, undefined)), - Effect.andThen(Deferred.await(readResult)), - ), - }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - yield* Deferred.await(readStarted); - yield* harness.provider.onSessionStarted(started, "/workspace"); - yield* harness.provider.onSessionStarted(started, "/other"); - const ready = yield* harness.provider.snapshot.getSnapshot; - expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } }); - expect(ready.usageLimits).toBeUndefined(); - expect(yield* Ref.get(reads)).toBe(1); - const limits = { - checkedAt: "2026-10-09T12:00:00.000Z", - windows: [ - { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }, - ], - } satisfies ServerProviderUsageLimits; - yield* Deferred.succeed(readResult, limits); - expect((yield* published)?.usageLimits).toEqual(limits); - }), - ), + Effect.gen(function* () { + const reads = yield* Ref.make(0); + const readStarted = yield* Deferred.make(); + const readResult = yield* Deferred.make(); + const harness = yield* makeHarness({ + probeUsage: Ref.update(reads, (count) => count + 1).pipe( + Effect.andThen(Deferred.succeed(readStarted, undefined)), + Effect.andThen(Deferred.await(readResult)), + ), + }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + yield* Deferred.await(readStarted); + yield* harness.provider.onSessionStarted(started, "/workspace"); + yield* harness.provider.onSessionStarted(started, "/other"); + const ready = yield* harness.provider.snapshot.getSnapshot; + expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } }); + expect(ready.usageLimits).toBeUndefined(); + expect(yield* Ref.get(reads)).toBe(1); + const limits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + } satisfies ServerProviderUsageLimits; + yield* Deferred.succeed(readResult, limits); + expect((yield* published)?.usageLimits).toEqual(limits); + }), ); it.effect("a quota read for the previous account is dropped after a new sign-in", () => - Effect.scoped( - Effect.gen(function* () { - const oldReadStarted = yield* Deferred.make(); - const newLimits = { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }], - } satisfies ServerProviderUsageLimits; - const usage = yield* Ref.make>( - Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)), - ); - const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); - const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); - yield* harness.initialize; - yield* Deferred.await(oldReadStarted); - yield* Ref.set(usage, Effect.succeed(newLimits)); - yield* harness.provider.onSignedIn; - yield* harness.provider.onSessionStarted(started); - expect((yield* published)?.usageLimits).toEqual(newLimits); - // Switching again must not republish the previous account's limits, even if the read fails. - const failed = { - checkedAt: "2026-10-09T12:02:00.000Z", - windows: [], - unavailable: { reason: "probeFailed" }, - } satisfies ServerProviderUsageLimits; - yield* Ref.set(usage, Effect.succeed(failed)); - const republished = yield* harness.nextPublish( - (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed", - ); - yield* harness.provider.onSignedIn; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); - yield* harness.provider.onSessionStarted(started); - expect((yield* republished)?.usageLimits).toEqual(failed); - }), - ), + Effect.gen(function* () { + const oldReadStarted = yield* Deferred.make(); + const newLimits = { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }], + } satisfies ServerProviderUsageLimits; + const usage = yield* Ref.make>( + Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)), + ); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); + const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + yield* Deferred.await(oldReadStarted); + yield* Ref.set(usage, Effect.succeed(newLimits)); + yield* harness.provider.onSignedIn; + yield* harness.provider.onSessionStarted(started); + expect((yield* published)?.usageLimits).toEqual(newLimits); + // Switching again must not republish the previous account's limits, even if the read fails. + const failed = { + checkedAt: "2026-10-09T12:02:00.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + } satisfies ServerProviderUsageLimits; + yield* Ref.set(usage, Effect.succeed(failed)); + const republished = yield* harness.nextPublish( + (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed", + ); + yield* harness.provider.onSignedIn; + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + yield* harness.provider.onSessionStarted(started); + expect((yield* republished)?.usageLimits).toEqual(failed); + }), ); }); diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index f969544fad064..18885f0417ebb 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -776,6 +776,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? resolvedEnvironment.ANTHROPIC_BASE_URL; const customApiEndpoint = customClaudeApiEndpointHost(baseUrl) !== undefined; + const endpoint = customApiEndpoint ? URL.parse(baseUrl?.trim() ?? "")?.origin : undefined; if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { const path = yield* Path.Path; const configDir = (yield* makeClaudeEnvironment(claudeSettings, resolvedEnvironment)) @@ -804,7 +805,9 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for. const authMetadata = apiProviderAuthMetadata(capabilities.apiProvider) ?? - (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined) ?? + (customApiEndpoint + ? { type: "customEndpoint", label: "Custom API endpoint", ...(endpoint ? { endpoint } : {}) } + : undefined) ?? claudeAuthMetadata({ subscriptionType: capabilities.subscriptionType, authMethod: capabilities.tokenSource, diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index 7eadf550eab28..ad15bf0896eb2 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import { applyPreferredCodexDefaultModel, + codexCustomEndpoint, codexRoutesSpendNativeQuota, mapCodexModelCapabilities, } from "./CodexProvider.ts"; @@ -192,4 +193,12 @@ it("reports native quota only for an OpenAI login on a native route", () => { name, ); } + // The custom endpoint is what a usage-limit hub is matched against. + assert.strictEqual(codexCustomEndpoint(hub), "https://hub.example.com"); + assert.strictEqual( + codexCustomEndpoint({ openai_base_url: "http://127.0.0.1:8317/v1" }), + "http://127.0.0.1:8317", + ); + assert.strictEqual(codexCustomEndpoint({ openai_base_url: "https://chatgpt.com/x" }), undefined); + assert.strictEqual(codexCustomEndpoint({}), undefined); }); diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index ab2cda61e53ee..df105d3ba20fe 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -57,7 +57,6 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import packageJson from "../../package.json" with { type: "json" }; const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError); -const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000; type CodexRateLimitsProbe = | { @@ -95,17 +94,21 @@ const CodexCyberAccessConfig = Schema.Struct({ }); const decodeCodexCyberAccessConfig = Schema.decodeUnknownOption(CodexCyberAccessConfig); -function routesToNativeOpenai(config: unknown): boolean { +// Null is Codex's auth-dependent OpenAI default; undefined is a route that cannot be read. +function codexRouteBaseUrl(config: unknown): string | null | undefined { const decoded = decodeCodexRoutingConfig(config); - if (Option.isNone(decoded)) return false; + if (Option.isNone(decoded)) return undefined; const routing = decoded.value; const providerId = routing.model_provider ?? "openai"; + if (providerId === "openai") return routing.openai_base_url || null; const provider = routing.model_providers?.[providerId]; - if (providerId !== "openai" && !provider) return false; - const baseUrl = - providerId === "openai" ? routing.openai_base_url || undefined : provider?.base_url; - // A provider without an override uses Codex's auth-dependent OpenAI default. - if (baseUrl == null) return true; + return provider ? (provider.base_url ?? null) : undefined; +} + +function routesToNativeOpenai(config: unknown): boolean { + const baseUrl = codexRouteBaseUrl(config); + if (baseUrl === undefined) return false; + if (baseUrl === null) return true; if (!URL.canParse(baseUrl)) return false; const url = new URL(baseUrl); return ( @@ -114,6 +117,15 @@ function routesToNativeOpenai(config: unknown): boolean { ); } +/** The origin of the custom endpoint Codex sends model requests to, if it uses one. */ +export function codexCustomEndpoint(config: unknown): string | undefined { + const baseUrl = codexRouteBaseUrl(config); + const url = baseUrl ? URL.parse(baseUrl) : null; + return url && /^https?:$/.test(url.protocol) && !routesToNativeOpenai(config) + ? url.origin + : undefined; +} + // A stored login does not mean this provider's traffic spends that login's quota. export const codexRoutesSpendNativeQuota = ( account: CodexSchema.V2GetAccountResponse, @@ -141,6 +153,7 @@ const CODEX_PRESENTATION = { export interface CodexAppServerProviderSnapshot { readonly account: CodexSchema.V2GetAccountResponse; + readonly endpoint?: string | undefined; readonly nativeUsage?: boolean; readonly rateLimits?: CodexRateLimitsProbe; readonly version: string | undefined; @@ -670,11 +683,7 @@ const readCodexRateLimits = ( client: CodexClient.CodexAppServerClient["Service"], deadlineMs: number, ) => - withCodexDiscoveryDeadline( - client.request("account/rateLimits/read", null), - deadlineMs, - RATE_LIMITS_PROBE_TIMEOUT_MS, - ).pipe( + withCodexDiscoveryDeadline(client.request("account/rateLimits/read", null), deadlineMs).pipe( Effect.map((response): CodexRateLimitsProbe => response ? { @@ -762,6 +771,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun const cyberAccess = Option.getOrUndefined(decodeCodexCyberAccessConfig(config)); return { account: accountResponse, + endpoint: config ? codexCustomEndpoint(config) : undefined, nativeUsage, ...(rateLimits ? { rateLimits } : {}), version, @@ -1080,7 +1090,9 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu installed: true, version: snapshot.version ?? null, status: snapshot.models === undefined ? "warning" : accountStatus.status, - auth: accountStatus.auth, + auth: snapshot.endpoint + ? { ...accountStatus.auth, endpoint: snapshot.endpoint } + : accountStatus.auth, ...(accountStatus.message ? { message: accountStatus.message } : snapshot.models === undefined diff --git a/apps/server/src/provider/CodexThreadRevert.test.ts b/apps/server/src/provider/CodexThreadRevert.test.ts index e48caf094027c..f268719154722 100644 --- a/apps/server/src/provider/CodexThreadRevert.test.ts +++ b/apps/server/src/provider/CodexThreadRevert.test.ts @@ -68,7 +68,6 @@ it.effect("finds the revert boundary across pages of newest-first turns", () => ], }), ), - Effect.scoped, ), ); @@ -87,6 +86,5 @@ it.effect("rejects repeated cursors instead of looping or reverting incomplete h entries: [...page(1, null, 3, ["newest"], "again"), ...page(2, "again", 2, [], "again")], }), ), - Effect.scoped, ), ); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 5cbf9f02bdb4a..447745fc673a0 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -444,7 +444,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { .map((request) => request.params?.value), ).toEqual(["default"]); } - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -464,7 +464,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(h.acquisitions).toHaveLength(2); expect(h.releases).toEqual([h.first.version, h.signedOut.version]); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () => @@ -481,7 +481,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(h.acquisitions).toHaveLength(2); expect(h.releases).toEqual([h.first.version]); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -502,7 +502,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(after.models).toEqual(before.models); expect(after.auth).toEqual(before.auth); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -539,7 +539,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(after.auth).toEqual(before.auth); expect(JSON.stringify(after)).not.toContain("sk-secret-123"); yield* h.assertClosed; - }).pipe(Effect.scoped), + }), ); it.effect.skipIf(windowsHost)( @@ -577,6 +577,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => { ); expect(yield* fs.exists(directories.runtimeTemp)).toBe(false); expect(yield* fs.exists(legacyRoot)).toBe(false); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 5060d8a24e5ed..c81b38a00dbcb 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -273,15 +273,43 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("rejects an oversized skill instead of returning an incomplete catalog", () => + it.effect("does not spend the scan budget on skill bodies", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); - const skillPath = yield* writeSkill( - path.join(input.cwd, ".agents", "skills", "oversized"), - `---\nname: oversized\ndescription: Read a large skill.\n---\n${"x".repeat(1_000_000)}`, + const root = path.join(input.userHome, ".gemini", "config", "skills"); + const expected = []; + for (let index = 0; index < 9; index += 1) { + const name = `large-${index}`; + const description = `Large skill ${index}. ${"y".repeat(2_000)}`; + const skillPath = yield* writeSkill( + path.join(root, name), + `---\nname: ${name}\ndescription: ${description}\n---\n${"x".repeat(950_000)}`, + ); + expected.push({ name, description, path: skillPath, scope: "user", enabled: true }); + } + + assert.deepEqual(yield* discoverAntigravitySkills(input), expected); + }), + ); + + it.effect("rejects frontmatter that does not close within the per-skill limit", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const input = yield* makeWorkspace(); + const root = path.join(input.cwd, ".agents", "skills"); + const largeBodyPath = yield* writeSkill( + path.join(root, "large-body"), + `---\nname: large-body\n---\n${"x".repeat(2_000_000)}`, ); + assert.deepEqual(yield* discoverAntigravitySkills(input), [ + { name: "large-body", path: largeBodyPath, scope: "project", enabled: true }, + ]); + const skillPath = yield* writeSkill( + path.join(root, "oversized"), + `---\nname: oversized\ndescription: ${"x".repeat(1_000_000)}\n---\n`, + ); const result = yield* discoverAntigravitySkills(input).pipe(Effect.result); assert.equal(result._tag, "Failure"); if (result._tag === "Failure") { @@ -291,7 +319,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("bounds the total read size across skills", () => + it.effect("bounds the total frontmatter read size across skills", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); @@ -299,7 +327,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { for (let index = 0; index < 9; index += 1) { yield* writeSkill( path.join(root, `large-${index}`), - `---\nname: large-${index}\n---\n${"x".repeat(900_000)}`, + `---\nname: large-${index}\ndescription: ${"x".repeat(900_000)}\n---\n`, ); } diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 19e9d8d293f48..96e1fe61109f4 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -37,6 +37,8 @@ export function antigravityUserSkillDirectories( const MAX_SKILL_BYTES = 1_000_000; const MAX_SCAN_BYTES = 8_000_000; const MAX_SCAN_ENTRIES = 10_000; +// Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget. +const SKILL_READ_CHUNK_BYTES = 1024; const SkillFrontmatter = Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)), @@ -106,7 +108,29 @@ function skillPathSortKey(entry: string) { ); } -const readSkill = Effect.fn("readAntigravitySkill")(function* ( +const DASH = 0x2d; + +/** Finds the byte offset after the second `---`, as parseSkillFrontmatter's indexOf calls do. */ +function makeFrontmatterEndFinder() { + let bytesSeen = 0; + let dashes = 0; + let markers = 0; + return (chunk: Uint8Array) => { + for (const byte of chunk) { + bytesSeen += 1; + dashes = byte === DASH ? dashes + 1 : 0; + if (dashes === 3) { + dashes = 0; + markers += 1; + if (markers === 2) return bytesSeen; + } + } + return undefined; + }; +} + +/** Reads through the frontmatter only, so skill bodies do not spend the scan budget. */ +const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( skillPath: string, budget: ScanBudget, ) { @@ -115,26 +139,27 @@ const readSkill = Effect.fn("readAntigravitySkill")(function* ( if (info?.type !== "File") return undefined; const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes); - if (info.size > BigInt(byteLimit)) { - return yield* new AntigravitySkillsProbeError({ - reason: "scan-budget-exhausted", - path: skillPath, - }); - } + const findFrontmatterEnd = makeFrontmatterEndFinder(); + let frontmatterEnd: number | undefined; const chunks = yield* readIfPresent( - fileSystem.stream(skillPath, { bytesToRead: byteLimit + 1 }).pipe(Stream.runCollect), + fileSystem + .stream(skillPath, { bytesToRead: byteLimit + 1, chunkSize: SKILL_READ_CHUNK_BYTES }) + .pipe( + Stream.takeUntil((chunk) => (frontmatterEnd = findFrontmatterEnd(chunk)) !== undefined), + Stream.runCollect, + ), skillPath, ); if (chunks === undefined) return undefined; const bytes = Buffer.concat(chunks); - if (bytes.byteLength > byteLimit) { + budget.remainingBytes -= bytes.byteLength; + if ((frontmatterEnd ?? bytes.byteLength) > byteLimit) { return yield* new AntigravitySkillsProbeError({ reason: "scan-budget-exhausted", path: skillPath, }); } - budget.remainingBytes -= bytes.byteLength; - return bytes.toString("utf8"); + return bytes.toString("utf8", 0, frontmatterEnd); }); /** Keep read errors typed so workspace snapshots cannot cache partial results. */ @@ -187,7 +212,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( if (skillFileName !== undefined) { if (!skillFileName.endsWith(".md")) return; const skillPath = path.join(directory, skillFileName); - const contents = yield* readSkill(skillPath, budget); + const contents = yield* readSkillFrontmatter(skillPath, budget); if (contents === undefined) return; const skill = parseSkillFrontmatter(contents, skillFileName); if (!skill || skillsByName.has(skill.name)) return; diff --git a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts index 6fdf4c52e2a98..7063df5023377 100644 --- a/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts @@ -239,7 +239,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ); yield* enrich; expect(requests).toHaveLength(1); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -297,7 +297,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ); yield* check; expect(requests).toHaveLength(3); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -317,7 +317,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ), ); expect((yield* resolve()).update?.lockKey).toBe(row.lockKey); - }).pipe(Effect.scoped), + }), ); it.effect("automatic refresh rereads the native channel while preserving both caches", () => @@ -403,7 +403,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { ]); expect(f.installationReads()).toBe(1); } - }).pipe(Effect.scoped), + }), ); it.effect("bounds stalled feed bodies and skips disabled update checks", () => @@ -433,6 +433,6 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => { yield* TestClock.adjust("4 seconds"); expect((yield* Fiber.join(pending)).versionAdvisory?.status).toBe("unknown"); expect(requests).toBe(1); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts index 6ce141eec733e..bdf2ed1cae61a 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts @@ -22,12 +22,14 @@ export interface ClaudeSkillDispatch { export function planClaudeSkillDispatch( prompt: string, skills: ReadonlyMap, + /** Mentions before this offset, such as inline handoff history, stay plain text. */ + mentionsFrom = 0, ): ClaudeSkillDispatch | undefined { const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => { const name = match[2] ?? ""; const skill = skills.get(name); - if (!skill) return []; const start = (match.index ?? 0) + (match[1]?.length ?? 0); + if (!skill || start < mentionsFrom) return []; return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }]; }); const last = mentions.at(-1); diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 597be85623115..6ce377a74a1e4 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -374,10 +374,7 @@ it.layer(layerTest)("CodexDriver", (it) => { lockKey: "codex-native", env: { CODEX_HOME: sharedHome }, }); - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect.skipIf(windowsHost)( @@ -431,10 +428,7 @@ it.layer(layerTest)("CodexDriver", (it) => { env: { CODEX_HOME: installHome }, }); } - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () => @@ -478,7 +472,7 @@ it.layer(layerTest)("CodexDriver", (it) => { CODEX_HOME: fixture.home, }); } - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); // regression: #23937 `codex update` installs the native channel's release, which can lag npm. @@ -556,10 +550,7 @@ it.layer(layerTest)("CodexDriver", (it) => { maintenanceCapabilities: capabilities, }).status, ).not.toBe("behind_latest"); - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); it.effect("uses each instance's environment CODEX_HOME for continuation", () => @@ -577,7 +568,36 @@ it.layer(layerTest)("CodexDriver", (it) => { }); expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`); } - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), + ); + + it.effect.skipIf(windowsHost)( + "shares state from the environment CODEX_HOME in a shadow home", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs + .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" }) + .pipe(Effect.flatMap((directory) => fs.realPath(directory))); + const codexHome = NodePath.join(tempDir, "custom-codex"); + const shadowHome = NodePath.join(tempDir, "shadow"); + yield* fs.makeDirectory(codexHome, { recursive: true }); + yield* fs.writeFileString(NodePath.join(codexHome, "config.toml"), 'model = "custom"\n'); + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("env-shadow"), + displayName: "env-shadow", + enabled: false, + environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }], + config: { ...CodexDriver.defaultConfig(), shadowHomePath: shadowHome }, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, NodePath.join(tempDir, "user"))); + expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`); + expect(yield* fs.readLink(NodePath.join(shadowHome, "config.toml"))).toBe( + NodePath.join(codexHome, "config.toml"), + ); + expect(yield* fs.readLink(NodePath.join(shadowHome, "sessions"))).toBe( + NodePath.join(codexHome, "sessions"), + ); + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); for (const fixture of [ @@ -653,10 +673,7 @@ it.layer(layerTest)("CodexDriver", (it) => { } else { expect(update).toBeNull(); } - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); } @@ -805,7 +822,7 @@ it.layer(layerTest)("CodexDriver", (it) => { } else { expect(capabilities.update).toBeNull(); } - }).pipe(Effect.scoped), + }), { skip: windowsHost }, ); @@ -856,6 +873,6 @@ it.layer(layerTest)("CodexDriver", (it) => { yield* TestClock.adjust("250 millis"); yield* Queue.take(probes); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 7e108315c4454..63dc8ac3f8fe0 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -191,11 +191,11 @@ export const CodexDriver: ProviderDriver< yield* HostProcess.Environment, ); const environmentHome = instanceEnv.CODEX_HOME; - const homeLayout = yield* resolveCodexHomeLayout( - !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome?.trim() + const homeConfig = + !config.homePath.trim() && environmentHome?.trim() ? { ...config, homePath: environmentHome } - : config, - ); + : config; + const homeLayout = yield* resolveCodexHomeLayout(homeConfig); const processEnv = withCodexSqliteHome(homeLayout, instanceEnv); const continuationIdentity = codexContinuationIdentity(homeLayout); const stampIdentity = withInstanceIdentity({ @@ -247,7 +247,7 @@ export const CodexDriver: ProviderDriver< accentColor, environment, enabled, - config, + config: homeConfig, }, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index c8c9fc9b4cae3..7f99d611c3de5 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -516,10 +516,7 @@ export const codexUsageReader: ProviderUsageReader< const path = yield* Path.Path; const environmentHome = environment.CODEX_HOME?.trim(); const layout = yield* resolveCodexHomeLayout( - config.setupMode !== "managed" && - !config.homePath.trim() && - !config.shadowHomePath.trim() && - environmentHome + config.setupMode !== "managed" && !config.homePath.trim() && environmentHome ? { ...config, homePath: environmentHome } : config, ); diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index be899ae540037..3f28649f498b8 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -639,7 +639,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount" ), ); expect(limits.windows[0]?.usedPercent).toBe(37); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -749,7 +749,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount" message: "Grok could not read usage limits.", }); } - }).pipe(Effect.scoped), + }), ); it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () => diff --git a/apps/server/src/provider/ModelManifest.test.ts b/apps/server/src/provider/ModelManifest.test.ts index e94ce85bf533c..0b4c4c062dca5 100644 --- a/apps/server/src/provider/ModelManifest.test.ts +++ b/apps/server/src/provider/ModelManifest.test.ts @@ -266,7 +266,7 @@ const layerService = (input: { ); describe("ModelManifest service", () => { - it.live("prefers a fetched manifest over the bundle and caches it to disk", () => + it.effect("prefers a fetched manifest over the bundle and caches it to disk", () => Effect.gen(function* () { const service = yield* ModelManifest.make; const refreshed = yield* service.refresh; @@ -285,29 +285,32 @@ describe("ModelManifest service", () => { ), ); - it.live("ignores older remote edits without replacing the current manifest or disk cache", () => { - let remote = { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" }; - return Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST); - assert.deepStrictEqual(yield* service.current, ModelManifest.BUNDLED_MODEL_MANIFEST); + it.effect( + "ignores older remote edits without replacing the current manifest or disk cache", + () => { + let remote = { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" }; + return Effect.gen(function* () { + const service = yield* ModelManifest.make; + assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST); + assert.deepStrictEqual(yield* service.current, ModelManifest.BUNDLED_MODEL_MANIFEST); - remote = { ...REMOTE_MANIFEST, updatedAt: REMOTE_UPDATED_AT }; - assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); - remote = { ...REMOTE_MANIFEST, updatedAt: ModelManifest.BUNDLED_MODEL_MANIFEST.updatedAt! }; - assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); - const rebooted = yield* ModelManifest.make; - assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-stale-fetch-test", - response: () => Response.json(remote), - }), - ), - ); - }); + remote = { ...REMOTE_MANIFEST, updatedAt: REMOTE_UPDATED_AT }; + assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); + remote = { ...REMOTE_MANIFEST, updatedAt: ModelManifest.BUNDLED_MODEL_MANIFEST.updatedAt! }; + assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); + const rebooted = yield* ModelManifest.make; + assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST); + }).pipe( + Effect.scoped, + Effect.provide( + layerService({ + prefix: "model-manifest-stale-fetch-test", + response: () => Response.json(remote), + }), + ), + ); + }, + ); it.effect("preserves the last-good remote cache when later payloads are invalid", () => { let responseIndex = 0; @@ -364,7 +367,7 @@ describe("ModelManifest service", () => { ); }); - it.live("drops a disk cache of a manifest older than the bundled one", () => + it.effect("drops a disk cache of a manifest older than the bundled one", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -400,7 +403,7 @@ describe("ModelManifest service", () => { ), ); - it.live("does not fetch when provider update checks are disabled", () => + it.effect("does not fetch when provider update checks are disabled", () => Effect.gen(function* () { let fetchCount = 0; const service = yield* ModelManifest.make.pipe( diff --git a/apps/server/src/provider/ProviderAuthService.test.ts b/apps/server/src/provider/ProviderAuthService.test.ts index 5023dc5bf47ef..603df5e7e4bcd 100644 --- a/apps/server/src/provider/ProviderAuthService.test.ts +++ b/apps/server/src/provider/ProviderAuthService.test.ts @@ -743,7 +743,7 @@ it.effect("queued logout prompts resolve the current controller after provider r assert.isTrue(yield* Fiber.join(queued)); assert.isTrue(replacementLoggedOut); assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1); - }).pipe(Effect.scoped), + }), ); it.effect.each(["start", "logout", "prompt"] as const)( @@ -814,7 +814,7 @@ it.effect.each(["start", "logout", "prompt"] as const)( const blocked = yield* Effect.flip(harness.service.logout({ instanceId })); assert.include(blocked.detail, "shared sign-in"); assert.equal(replacementMutations, 0); - }).pipe(Effect.scoped), + }), ); it.effect.each(["selection", "drain"] as const)( @@ -855,5 +855,5 @@ it.effect.each(["selection", "drain"] as const)( assert.notInclude(harness.actions, "stop:peer-persisted"); assert.isFalse(harness.sessions.has(ThreadId.make("target-draining"))); assert.include(harness.actions, "native-logout"); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index ab35fe4d9ae59..707275afc97d2 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -346,7 +346,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () => + it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); const configMap: ProviderInstanceConfigMap = { @@ -370,7 +370,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("lists a blocked driver's instances as unavailable without running them", () => + it.effect("lists a blocked driver's instances as unavailable without running them", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("codex"); const reason = "Example Corp's policy does not allow the Codex provider."; @@ -862,7 +862,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { ); } - it.live( + it.effect( "shadows instances whose driver is not registered in this build without failing boot", () => Effect.gen(function* () { @@ -990,7 +990,7 @@ describe("ProviderInstanceRegistry secret environment", () => { { name: "BASE_URL", value: "https://example.test", sensitive: false }, ], ]); - }).pipe(Effect.scoped); + }); }); // An empty secret must not let a driver fall back to a credential the server inherited. @@ -1013,7 +1013,7 @@ describe("ProviderInstanceRegistry secret environment", () => { yield* mutator.reconcile({ ...fixture.configMap }); expect(fixture.reads).toHaveLength(readsAtStartup); expect(yield* registry.listUnavailable).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("does not read the secrets of an instance its config decodes as disabled", () => { @@ -1025,7 +1025,7 @@ describe("ProviderInstanceRegistry secret environment", () => { expect(fixture.reads).toEqual([]); expect(fixture.invalidated).toEqual([]); expect(fixture.created).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("re-reads secrets on reload and rebuilds only when they changed", () => { @@ -1048,7 +1048,7 @@ describe("ProviderInstanceRegistry secret environment", () => { "sk-live", "sk-rotated", ]); - }).pipe(Effect.scoped); + }); }); it.effect("reads a config field typed SettingsSecretValue and rebuilds when it rotates", () => { @@ -1068,7 +1068,7 @@ describe("ProviderInstanceRegistry secret environment", () => { { apiKey: "gw-live", model: "m" }, { apiKey: "gw-rotated", model: "m" }, ]); - }).pipe(Effect.scoped); + }); }); it.effect.each([ @@ -1084,7 +1084,7 @@ describe("ProviderInstanceRegistry secret environment", () => { return Effect.gen(function* () { yield* fixture.make; expect(fixture.configs).toEqual([expect.objectContaining({ [field]: "provider-live" })]); - }).pipe(Effect.scoped); + }); }); it.effect("keeps a working instance live when a reload cannot read its secret", () => { @@ -1098,7 +1098,7 @@ describe("ProviderInstanceRegistry secret environment", () => { expect(yield* registry.getInstance(instanceId)).toBeDefined(); expect(yield* registry.listUnavailable).toEqual([]); expect(fixture.created).toHaveLength(1); - }).pipe(Effect.scoped); + }); }); it.effect("starts without waiting for secrets to be read", () => { @@ -1115,6 +1115,6 @@ describe("ProviderInstanceRegistry secret environment", () => { yield* PubSub.take(changes); expect(yield* registry.getInstance(instanceId)).toBeDefined(); expect(yield* registry.listUnavailable).toEqual([]); - }).pipe(Effect.scoped); + }); }); }); diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 0601714dd618e..564a90f40e6ce 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -17,6 +17,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -788,6 +789,86 @@ it.layer( }), ); + it.effect("shows Codex usage that answers after three seconds inside the probe budget", () => + Effect.gen(function* () { + const usageRequested = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Effect.scope; + const output = yield* Queue.unbounded(); + const send = (message: unknown) => + Queue.offer(output, encoder.encode(`${JSON.stringify(message)}\n`)); + const results: Record = { + initialize: { + userAgent: "codex_cli_rs/0.167.0", + codexHome: "/nonexistent-codex-home", + platformFamily: "unix", + platformOs: "linux", + }, + "account/read": { + account: { type: "chatgpt", email: "test@example.com", planType: "pro" }, + requiresOpenaiAuth: true, + }, + "config/read": { config: {}, origins: {} }, + "skills/list": { data: [] }, + "model/list": { data: [] }, + }; + const answer = (line: string) => { + const { id, method } = JSON.parse(line) as { id?: number; method?: string }; + if (id === undefined || method === undefined) return Effect.void; + if (method !== "account/rateLimits/read") { + return send({ id, result: results[method] ?? {} }); + } + return Deferred.succeed(usageRequested, undefined).pipe( + Effect.andThen(Effect.sleep("4 seconds")), + Effect.andThen( + send({ + id, + result: { + rateLimits: { + limitId: "codex", + planType: "pro", + primary: { usedPercent: 42, windowDurationMins: 300, resetsAt: 2e9 }, + }, + rateLimitsByLimitId: null, + rateLimitResetCredits: null, + accountId: null, + }, + }), + ), + Effect.forkIn(scope), + ); + }; + const decoder = new TextDecoder(); + let buffered = ""; + return ChildProcessSpawner.makeHandle({ + ...mockHandle({ stdout: "", stderr: "", code: 0 }), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + stdin: Sink.forEach((chunk: Uint8Array) => { + buffered += decoder.decode(chunk, { stream: true }); + const lines = buffered.split("\n"); + buffered = lines.pop() ?? ""; + return Effect.forEach(lines.filter(Boolean), answer, { discard: true }); + }), + stdout: Stream.fromQueue(output), + }); + }), + ); + const fiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.forkChild, + ); + yield* Deferred.await(usageRequested); + yield* TestClock.adjust("25 seconds"); + const status = yield* Fiber.join(fiber); + + assert.strictEqual(status.auth.status, "authenticated"); + assert.isUndefined(status.usageLimits?.unavailable); + assert.strictEqual(status.usageLimits?.windows[0]?.usedPercent, 42); + }), + ); + it.effect("does not run --version when the Codex executable cannot start", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; diff --git a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts index 795e80b861e84..81885dc0c89b2 100644 --- a/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts +++ b/apps/server/src/provider/acp/AntigravitySessionFiles.test.ts @@ -31,7 +31,7 @@ it.layer(NodeServices.layer)("retireAntigravityRuntimeTempDirs", (it) => { yield* removeRetired; expect((yield* fs.readDirectory(parent)).toSorted()).toEqual(["other-instance"]); - }).pipe(Effect.scoped), + }), ); it.effect( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 09b8730bd6001..52e96caa08aea 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -158,7 +158,7 @@ describe("watchAntigravityPromptOutcome", () => { code: "QUOTA_EXHAUSTED", retryable: true, }); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("reads only this session's own unlinked log, and keeps a typed refusal", () => @@ -206,6 +206,6 @@ describe("watchAntigravityPromptOutcome", () => { code: "QUOTA_EXHAUSTED", retryable: true, }); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 33b90ef2796ea..f789448ab5dbd 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 5597, - "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 58309 + "claudeSystemAppendBytes": 5594, + "codexAdditionalContextBytes": 7324, + "mcpToolListJsonBytes": 58304 } diff --git a/apps/server/src/provider/claudeUsageLimits.test.ts b/apps/server/src/provider/claudeUsageLimits.test.ts index 311e747253486..f345b7d7077c6 100644 --- a/apps/server/src/provider/claudeUsageLimits.test.ts +++ b/apps/server/src/provider/claudeUsageLimits.test.ts @@ -223,6 +223,22 @@ describe("claudeUsageResponseToLimits", () => { ).toEqual([monthlyWindow]); }); + it("flags a $0 cap instead of reporting a monthly window", () => { + const response = { + rate_limits_available: true, + rate_limits: { + five_hour: null, + seven_day: null, + extra_usage: { is_enabled: true, used_credits: 0, monthly_limit: 0, utilization: null }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits).toEqual({ + checkedAt, + windows: [], + zeroSpendCap: true, + }); + }); + it("omits disabled budgets and refuses invalid money without an enabled fallback", () => { const rateLimits = enterpriseResponse.rate_limits; const response = { diff --git a/apps/server/src/provider/claudeUsageLimits.ts b/apps/server/src/provider/claudeUsageLimits.ts index eb658129b58b9..440d34636f031 100644 --- a/apps/server/src/provider/claudeUsageLimits.ts +++ b/apps/server/src/provider/claudeUsageLimits.ts @@ -70,8 +70,20 @@ export const makeClaudeScopedLimitNames = Ref.make({ overageIncluded: undefined, }); +const SCOPED_WINDOW_PREFIX = "seven_day_"; +const scopeToken = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, "_"); + function scopedWindowId(displayName: string): string { - return `seven_day_${displayName.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`; + return `${SCOPED_WINDOW_PREFIX}${scopeToken(displayName)}`; +} + +/** A model-scoped weekly allowance blocks only its own model; an unknown model is not blocked. */ +export function windowLimitsModel( + window: Pick, + model: string | null, +): boolean { + if (!window.id.startsWith(SCOPED_WINDOW_PREFIX)) return true; + return model !== null && scopeToken(model).includes(window.id.slice(SCOPED_WINDOW_PREFIX.length)); } function scopedWindow( @@ -225,6 +237,7 @@ export function claudeUsageResponseToLimits(input: { overageIncluded ??= entry.display_name; } const spendPercent = readSpendPercent(response.rate_limits); + const extra = response.rate_limits.extra_usage; if (spendPercent !== undefined) { windows.push({ id: "monthly_spend", @@ -234,7 +247,10 @@ export function claudeUsageResponseToLimits(input: { }); } return { - limits: makeUsageLimits({ checkedAt, windows }), + limits: { + ...makeUsageLimits({ checkedAt, windows }), + ...(extra?.is_enabled && extra.monthly_limit === 0 ? { zeroSpendCap: true } : {}), + }, names: { overageIncluded }, }; } diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.ts index cbca3037c26d1..d55f7913ed605 100644 --- a/apps/server/src/provider/providerCompatibility.test.ts +++ b/apps/server/src/provider/providerCompatibility.test.ts @@ -343,5 +343,5 @@ it.effect("a remote policy refresh preserves a newer health result on the regist ), ), ); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts index 3ee929f923a57..200ea36b7d64d 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts @@ -390,208 +390,198 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"], }, ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) => - Effect.scoped( - Effect.gen(function* () { - const run = yield* startSingleBranchRun({ - repositoryName: "refused-head", - reportedHead, - refuseCommitFetch: false, - prepare: (repositories, workspace) => - git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe( - Effect.andThen( - shadow === "none" - ? Effect.void - : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]), - ), - Effect.asVoid, + Effect.gen(function* () { + const run = yield* startSingleBranchRun({ + repositoryName: "refused-head", + reportedHead, + refuseCommitFetch: false, + prepare: (repositories, workspace) => + git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe( + Effect.andThen( + shadow === "none" + ? Effect.void + : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]), ), - }); - const result = yield* run.settled; - assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written"); - assert.strictEqual(result.run?._tag, "Failed"); - const detail = result.run?._tag === "Failed" ? result.run.detail : ""; - for (const part of expected) assert.include(detail, part); - // Only the host's own head ref is tried. - assert.notInclude(detail, "refs/merge-requests/"); - assert.deepStrictEqual(run.observed, []); - assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-"))); - const fs = yield* FileSystem.FileSystem; - assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`)); - }), - ), + Effect.asVoid, + ), + }); + const result = yield* run.settled; + assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written"); + assert.strictEqual(result.run?._tag, "Failed"); + const detail = result.run?._tag === "Failed" ? result.run.detail : ""; + for (const part of expected) assert.include(detail, part); + // Only the host's own head ref is tried. + assert.notInclude(detail, "refs/merge-requests/"); + assert.deepStrictEqual(run.observed, []); + assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-"))); + const fs = yield* FileSystem.FileSystem; + assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`)); + }), ); it.effect("measures only the PR change using the renamed verified remote's fetch URL", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", "main~1"]); - // The cached identity still names origin, which now belongs to the stale fork. - yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); - yield* git(repositories.workspace, ["remote", "add", "origin", fork]); - yield* git(repositories.workspace, [ - "config", - `url.${repositories.remote}.insteadOf`, - "review-upstream:", - ]); - yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); - const changed = yield* Deferred.make(); - const driver = yield* GitVcsDriver.GitVcsDriver; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: (input) => - git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, driver), - Effect.orDie, - Effect.flatMap((names) => Deferred.succeed(changed, names)), - Effect.as({ stops: [] }), - ), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - yield* service.generate(reference); - assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); - yield* Deferred.await(stored); - const result = yield* service.get(reference); - assert.strictEqual(result.guide?.headSha, repositories.headSha); - assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", "main~1"]); + // The cached identity still names origin, which now belongs to the stale fork. + yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); + yield* git(repositories.workspace, ["remote", "add", "origin", fork]); + yield* git(repositories.workspace, [ + "config", + `url.${repositories.remote}.insteadOf`, + "review-upstream:", + ]); + yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); + const changed = yield* Deferred.make(); + const driver = yield* GitVcsDriver.GitVcsDriver; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: (input) => + git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + Effect.orDie, + Effect.flatMap((names) => Deferred.succeed(changed, names)), + Effect.as({ stops: [] }), + ), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + yield* service.generate(reference); + assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); + yield* Deferred.await(stored); + const result = yield* service.get(reference); + assert.strictEqual(result.guide?.headSha, repositories.headSha); + assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); + }), ); it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fs = yield* FileSystem.FileSystem; - yield* fs.writeFileString( - `${repositories.workspace}/.git/info/attributes`, - "feature.txt diff=blank\n", - ); - yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]); - const hook = `${repositories.workspace}/.git/hooks/post-checkout`; - yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n"); - yield* fs.chmod(hook, 0o755); - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: () => - Effect.succeed({ - stops: [ - { - title: "The feature", - summary: "The change.", - attention: null, - excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }], - files: [], - notes: [], - questions: [], - }, - ], - }), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const runs = yield* watchRuns; - yield* runs.generate(service, reference); - const result = yield* runs.settled(service, reference); - assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run)); - assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [ - { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }, - ]); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString( + `${repositories.workspace}/.git/info/attributes`, + "feature.txt diff=blank\n", + ); + yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]); + const hook = `${repositories.workspace}/.git/hooks/post-checkout`; + yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(hook, 0o755); + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: () => + Effect.succeed({ + stops: [ + { + title: "The feature", + summary: "The change.", + attention: null, + excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }], + files: [], + notes: [], + questions: [], + }, + ], + }), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const runs = yield* watchRuns; + yield* runs.generate(service, reference); + const result = yield* runs.settled(service, reference); + assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run)); + assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [ + { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }, + ]); + }), ); it.effect("refuses generation when the verified remote disappeared despite a usable origin", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", repositories.lowerSha]); - yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]); - const started = yield* Deferred.make>(); - const stored = yield* Deferred.make(); - const generated = yield* Ref.make(false); - const driver = yield* GitVcsDriver.GitVcsDriver; - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })), - }).pipe( - Layer.provide( - Layer.succeed(GitVcsDriver.GitVcsDriver, { - ...driver, - execute: (call) => - Effect.withFiber((fiber) => - Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))), - ), - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", repositories.lowerSha]); + yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]); + const started = yield* Deferred.make>(); + const stored = yield* Deferred.make(); + const generated = yield* Ref.make(false); + const driver = yield* GitVcsDriver.GitVcsDriver; + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })), + }).pipe( + Layer.provide( + Layer.succeed(GitVcsDriver.GitVcsDriver, { + ...driver, + execute: (call) => + Effect.withFiber((fiber) => + Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))), + ), + }), ), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const before = yield* service.get(reference); - yield* service.generate(reference); - // Join the background run so its failure is visible without polling service state. - yield* Fiber.await(yield* Deferred.await(started)); - const result = yield* service.get(reference); - assert.strictEqual(result.run?._tag, "Failed"); - assert.include( - result.run?._tag === "Failed" ? result.run.detail : "", - "no longer has a remote for the pull request's repository", - ); - assert.deepStrictEqual(result.guide, before.guide); - assert.isFalse(yield* Deferred.isDone(stored)); - assert.isFalse(yield* Ref.get(generated)); - }), - ), + ), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const before = yield* service.get(reference); + yield* service.generate(reference); + // Join the background run so its failure is visible without polling service state. + yield* Fiber.await(yield* Deferred.await(started)); + const result = yield* service.get(reference); + assert.strictEqual(result.run?._tag, "Failed"); + assert.include( + result.run?._tag === "Failed" ? result.run.detail : "", + "no longer has a remote for the pull request's repository", + ); + assert.deepStrictEqual(result.guide, before.guide); + assert.isFalse(yield* Deferred.isDone(stored)); + assert.isFalse(yield* Ref.get(generated)); + }), ); it.effect("refuses a pull request from a repository the project is not a checkout of", () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - identity: { - ...ACME_APP, - canonicalKey: "github.com/acme/other", - displayName: "acme/other", - name: "other", - }, - generate: () => - Effect.die("a guide must not be written from another repository's checkout"), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - const result = yield* Effect.flip(service.generate(reference)); - assert.include(result.message, "in another repository"); - }), - ), + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + stored, + identity: { + ...ACME_APP, + canonicalKey: "github.com/acme/other", + displayName: "acme/other", + name: "other", + }, + generate: () => + Effect.die("a guide must not be written from another repository's checkout"), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + const result = yield* Effect.flip(service.generate(reference)); + assert.include(result.message, "in another repository"); + }), ); }); diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 7e40e43b55e0d..773d0c6b6adee 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -1429,174 +1429,160 @@ it.effect( ); it.effect("publishes a merge for immediate settlement only after host confirmation", () => - Effect.scoped( - Effect.gen(function* () { - const mergedAt = "2026-09-03T02:00:00.000Z"; - let state: "open" | "merged" = "open"; - let confirmationFails = false; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - confirmationFails - ? Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequestSummary", - reason: "failed", - detail: "HTTP 504", - }), - ) - : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); + Effect.gen(function* () { + const mergedAt = "2026-09-03T02:00:00.000Z"; + let state: "open" | "merged" = "open"; + let confirmationFails = false; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + confirmationFails + ? Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "getChangeRequestSummary", + reason: "failed", + detail: "HTTP 504", + }), + ) + : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); - assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); - const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); - confirmationFails = true; - yield* service.runAction({ ...reference, action: "merge" }); - assert.isAbove( - Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), - queuedRefresh, - ); - confirmationFails = false; - state = "merged"; - // The event carries the host's merge time, not the moment the confirmation ran. - yield* TestClock.setTime(Date.parse(mergedAt) + 60_000); - yield* service.runAction({ - ...reference, - repository: " ACME/WEB ", - action: "merge", - mergeMethod: "merge", - }); + assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); + const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); + confirmationFails = true; + yield* service.runAction({ ...reference, action: "merge" }); + assert.isAbove( + Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), + queuedRefresh, + ); + confirmationFails = false; + state = "merged"; + // The event carries the host's merge time, not the moment the confirmation ran. + yield* TestClock.setTime(Date.parse(mergedAt) + 60_000); + yield* service.runAction({ + ...reference, + repository: " ACME/WEB ", + action: "merge", + mergeMethod: "merge", + }); - assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { - ...reference, - mergedAt, - }); - }), - ), + assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { + ...reference, + mergedAt, + }); + }), ); it.effect("returns the host's merged reply as a summary and trusts it without another read", () => - Effect.scoped( - Effect.gen(function* () { - const mergedAt = "2026-09-03T02:00:00.000Z"; - const merged = { - number: 1, - title: "Change request 1", - url: "https://host/pull/1", - headBranch: "feat/1", - baseBranch: "main", - state: "merged" as const, - isDraft: false, - updatedAt: mergedAt, - mergedAt, - headSha: "abc123", - autoMergeEnabled: false, - }; - let summaryReads = 0; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - runAction: () => Effect.succeed(merged), - getChangeRequestSummary: () => - Effect.sync(() => { - summaryReads++; - return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt }; - }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); - const observedAt = Date.parse("2026-09-03T02:00:01.000Z"); - yield* TestClock.setTime(observedAt); - - // Clients that did not ask decode the success as void, so they must get nothing back. - assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); - const result = yield* service.runAction({ - ...reference, - action: "merge", - replyWithSummary: true, - }); + Effect.gen(function* () { + const mergedAt = "2026-09-03T02:00:00.000Z"; + const merged = { + number: 1, + title: "Change request 1", + url: "https://host/pull/1", + headBranch: "feat/1", + baseBranch: "main", + state: "merged" as const, + isDraft: false, + updatedAt: mergedAt, + mergedAt, + headSha: "abc123", + autoMergeEnabled: false, + }; + let summaryReads = 0; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + runAction: () => Effect.succeed(merged), + getChangeRequestSummary: () => + Effect.sync(() => { + summaryReads++; + return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt }; + }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); + const observedAt = Date.parse("2026-09-03T02:00:01.000Z"); + yield* TestClock.setTime(observedAt); - assert.deepStrictEqual(result, { - ...merged, - provider: SourceControlProviderKind.make("github"), - projectId: reference.projectId, - repository: reference.repository, - observedAt, - }); - assert.strictEqual(summaryReads, 0); - assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { - ...reference, - mergedAt, - }); - }), - ), + // Clients that did not ask decode the success as void, so they must get nothing back. + assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" })); + const result = yield* service.runAction({ + ...reference, + action: "merge", + replyWithSummary: true, + }); + + assert.deepStrictEqual(result, { + ...merged, + provider: SourceControlProviderKind.make("github"), + projectId: reference.projectId, + repository: reference.repository, + observedAt, + }); + assert.strictEqual(summaryReads, 0); + assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), { + ...reference, + mergedAt, + }); + }), ); it.effect("refreshes every reader before a queued merge confirmation finishes", () => - Effect.scoped( - Effect.gen(function* () { - const confirmationStarted = yield* Deferred.make(); - const confirm = yield* Deferred.make(); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.gen(function* () { - yield* Deferred.succeed(confirmationStarted, undefined); - yield* Deferred.await(confirm); - return changeRequest(1, "2026-09-16T00:00:00.000Z"); - }), - }), - ], - }); - const merges = yield* service.subscribeMerges; - const observedMerge = yield* Stream.runHead(merges).pipe( - Effect.forkChild({ startImmediately: true }), - ); - const readers = yield* Effect.forEach([0, 1], () => - Stream.runHead(service.subscribeRefreshes).pipe( - Effect.forkChild({ startImmediately: true }), - ), - ); - const action = yield* service - .runAction({ ...reference, action: "merge" }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(confirmationStarted); - const revisions = yield* Effect.forEach(readers, (reader) => - Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)), - ); - assert.isAbove(revisions[0]!, 0); - assert.strictEqual(revisions[0], revisions[1]); - assert.isUndefined(action.pollUnsafe()); - yield* Deferred.succeed(confirm, undefined); - yield* Fiber.join(action); - assert.isUndefined(observedMerge.pollUnsafe()); - }), - ), + Effect.gen(function* () { + const confirmationStarted = yield* Deferred.make(); + const confirm = yield* Deferred.make(); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.gen(function* () { + yield* Deferred.succeed(confirmationStarted, undefined); + yield* Deferred.await(confirm); + return changeRequest(1, "2026-09-16T00:00:00.000Z"); + }), + }), + ], + }); + const merges = yield* service.subscribeMerges; + const observedMerge = yield* Stream.runHead(merges).pipe( + Effect.forkChild({ startImmediately: true }), + ); + const readers = yield* Effect.forEach([0, 1], () => + Stream.runHead(service.subscribeRefreshes).pipe(Effect.forkChild({ startImmediately: true })), + ); + const action = yield* service + .runAction({ ...reference, action: "merge" }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(confirmationStarted); + const revisions = yield* Effect.forEach(readers, (reader) => + Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)), + ); + assert.isAbove(revisions[0]!, 0); + assert.strictEqual(revisions[0], revisions[1]); + assert.isUndefined(action.pollUnsafe()); + yield* Deferred.succeed(confirm, undefined); + yield* Fiber.join(action); + assert.isUndefined(observedMerge.pollUnsafe()); + }), ); it.effect("runs branch deletion only when the host and viewer support it, never for a stack", () => @@ -2864,56 +2850,52 @@ it.effect("a read during a refresh cannot keep the provider's old change request ); it.effect("close and reopen notify subscribed readers after invalidating their cached state", () => - Effect.scoped( - Effect.gen(function* () { - let hostCalls = 0; - let state: "open" | "closed" = "open"; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), - runAction: (input) => - Effect.sync(() => { - state = input.action === "close" ? "closed" : "open"; - }), - listChangeRequests: () => { - hostCalls += 1; - return Effect.succeed({ items: [], truncated: false, continues: false }); - }, - }), - ], - }); - - yield* service.refreshAfterTurn(reference.projectId); - yield* service.list({ state: "open" }); - assert.strictEqual((yield* service.summary(reference)).state, "open"); - for (const action of ["close", "reopen"] as const) { - const refreshed = yield* service.subscribeRefreshes.pipe( - Stream.drop(1), - Stream.take(1), - Stream.mapEffect(() => - Effect.gen(function* () { - yield* service.list({ state: "open" }); - return yield* service.summary(reference); + Effect.gen(function* () { + let hostCalls = 0; + let state: "open" | "closed" = "open"; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), + runAction: (input) => + Effect.sync(() => { + state = input.action === "close" ? "closed" : "open"; }), - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - yield* service.runAction({ ...reference, action }); - assert.strictEqual( - Option.getOrThrow(yield* Fiber.join(refreshed)).state, - action === "close" ? "closed" : "open", - ); - } - assert.strictEqual(hostCalls, 3); - }), - ), + listChangeRequests: () => { + hostCalls += 1; + return Effect.succeed({ items: [], truncated: false, continues: false }); + }, + }), + ], + }); + + yield* service.refreshAfterTurn(reference.projectId); + yield* service.list({ state: "open" }); + assert.strictEqual((yield* service.summary(reference)).state, "open"); + for (const action of ["close", "reopen"] as const) { + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.drop(1), + Stream.take(1), + Stream.mapEffect(() => + Effect.gen(function* () { + yield* service.list({ state: "open" }); + return yield* service.summary(reference); + }), + ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* service.runAction({ ...reference, action }); + assert.strictEqual( + Option.getOrThrow(yield* Fiber.join(refreshed)).state, + action === "close" ? "closed" : "open", + ); + } + assert.strictEqual(hostCalls, 3); + }), ); it.effect("reads a host's repositories in one search, and files the rows back under each", () => diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 943fdc55d1d50..2f79c4b524eeb 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -224,6 +224,9 @@ export class PullRequestService extends Context.Service< input: PullRequestReportStateInput, ) => Effect.Effect; readonly subscribeRefreshes: Stream.Stream; + readonly subscribeLinkedThreadRefreshes: Stream.Stream; + /** Wakes linked-thread readers only; other pull request reads don't depend on thread links. */ + readonly notifyLinkedThreadsChanged: Effect.Effect; readonly refreshAfterTurn: ( projectId: ProjectId, options?: { readonly pushed?: boolean }, @@ -738,6 +741,7 @@ export const make = Effect.gen(function* () { const mergedPullRequests = yield* PubSub.sliding(64); const stateChanges = yield* PubSub.sliding(64); const pullRequestRefreshes = yield* SubscriptionRef.make(0); + const linkedThreadRefreshes = yield* SubscriptionRef.make(0); const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry; const requirementOf: UnavailableRequirementOf = (kind) => registry.get(kind)?.unavailableRequirement; @@ -3687,6 +3691,11 @@ export const make = Effect.gen(function* () { yield* SubscriptionRef.set(pullRequestRefreshes, epoch); }); + const notifyLinkedThreadsChanged = SubscriptionRef.update( + linkedThreadRefreshes, + (revision) => revision + 1, + ); + const invalidatedByMutation = ( method: (input: I) => Effect.Effect, @@ -3886,6 +3895,10 @@ export const make = Effect.gen(function* () { subscribeRefreshes: SubscriptionRef.changes(pullRequestRefreshes).pipe( Stream.filter((revision) => revision > 0), ), + subscribeLinkedThreadRefreshes: SubscriptionRef.changes(linkedThreadRefreshes).pipe( + Stream.filter((revision) => revision > 0), + ), + notifyLinkedThreadsChanged, refreshAfterTurn, detail: credentialCached(detail), checks: credentialCached((input) => Cache.get(checksCache, refCacheKey(input))), diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.ts index 8992a32ea10ca..2dac788641586 100644 --- a/apps/server/src/pullRequest/linkedThreads.test.ts +++ b/apps/server/src/pullRequest/linkedThreads.test.ts @@ -1,10 +1,18 @@ +import { + ProjectId, + ThreadId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ThreadPullRequestLink, +} from "@t3tools/contracts"; import { assert, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; -import { listLinkedPullRequestThreads } from "./linkedThreads.ts"; +import { listLinkedPullRequestThreads, makeLinkedThreadsChangeDetector } from "./linkedThreads.ts"; const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -209,3 +217,132 @@ it.effect( ); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it("signals linked-thread changes only when a linked answer could change", () => { + const now = DateTime.makeUnsafe("2026-11-12T00:00:00.000Z"); + const threadId = ThreadId.make("thread-a"); + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "acme/web", + number: 7, + url: "https://github.com/acme/web/pull/7", + source: "agent", + linkedAt: "2026-11-12T00:00:00.000Z", + snapshot: null, + stack: null, + }; + const base = { + id: threadId, + projectId: ProjectId.make("project-a"), + title: "Thread A", + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + updatedAt: now, + } as unknown as OrchestrationV2AppThread; + const event = ( + type: OrchestrationV2DomainEvent["type"], + payload: Partial, + ) => ({ type, threadId, payload: { ...base, ...payload } }) as OrchestrationV2DomainEvent; + const changed = makeLinkedThreadsChangeDetector(); + + expect( + [ + event("thread.metadata-updated", { title: "Unlinked rename" }), + event("thread.pull-request-synced", { pullRequests: [link] }), + event("thread.pull-request-synced", { + pullRequests: [{ ...link, watch: { since: "2026-11-12T00:00:00.000Z" } as never }], + }), + event("thread.visited", { pullRequests: [link] }), + event("thread.pinned", { pullRequests: [link], settledAt: now }), + { type: "thread.pull-request-link-updated", threadId, payload: link } as never, + event("thread.metadata-updated", { pullRequests: [link], title: "Renamed" }), + event("thread.archived", { pullRequests: [link], title: "Renamed", archivedAt: now }), + event("thread.pull-request-synced", { + pullRequests: [{ ...link, source: "stack-dismissed" }], + title: "Renamed", + archivedAt: now, + }), + event("thread.deleted", { pullRequests: [], deletedAt: now }), + ].map(changed), + ).toEqual([ + "changed", + "changed", + null, + null, + "changed", + null, + "changed", + "changed", + "changed", + null, + ]); + + const afterRestart = makeLinkedThreadsChangeDetector(); + expect(afterRestart(event("thread.created", { title: "New" }))).toBe(null); + expect( + makeLinkedThreadsChangeDetector()( + event("thread.deleted", { pullRequests: [], deletedAt: now }), + ), + ).toBe("changed"); +}); + +it("signals when activity reorders the threads linked to a pull request", () => { + const at = (second: number) => DateTime.makeUnsafe(`2026-11-12T00:00:0${second}.000Z`); + const link = { + host: "github.com", + repository: "acme/web", + number: 7, + url: "https://github.com/acme/web/pull/7", + source: "agent", + }; + const thread = (id: string, second: number, pullRequests: ReadonlyArray = [link]) => + ({ + type: "thread.pull-request-synced", + threadId: ThreadId.make(id), + payload: { + id: ThreadId.make(id), + projectId: ProjectId.make("project-a"), + title: id, + lineage: { rootThreadId: ThreadId.make(id) }, + pullRequests, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + updatedAt: at(second), + }, + }) as unknown as OrchestrationV2DomainEvent; + const activity = (id: string, second: number) => + ({ + type: "message.updated", + threadId: ThreadId.make(id), + occurredAt: at(second), + }) as unknown as OrchestrationV2DomainEvent; + const changed = makeLinkedThreadsChangeDetector(); + changed(thread("a", 1)); + changed(thread("b", 2)); + + expect( + [ + { ...thread("a", 3), type: "thread.pinned" } as OrchestrationV2DomainEvent, + activity("a", 4), + activity("b", 5), + activity("b", 5), + // Seen since startup without links, so its activity can't reorder an answer. + thread("unlinked", 5, []), + activity("unlinked", 6), + // Not seen since startup, so it may be linked from before the restart. + activity("persisted", 6), + ].map(changed), + ).toEqual(["reordered", "reordered", "reordered", null, "changed", null, "reordered"]); + + // Other threads linked to the pull request may have had no event since the restart. + const afterRestart = makeLinkedThreadsChangeDetector(); + afterRestart(thread("a", 2)); + expect( + afterRestart({ ...thread("a", 6), type: "thread.pinned" } as OrchestrationV2DomainEvent), + ).toBe("reordered"); +}); diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts index 87ffae525eb9c..1fb6b5f5dfebf 100644 --- a/apps/server/src/pullRequest/linkedThreads.ts +++ b/apps/server/src/pullRequest/linkedThreads.ts @@ -1,12 +1,18 @@ import { normalizeThreadPullRequestKey, + threadPullRequestKeyOf, threadPullRequestKeysEqual, + visibleThreadPullRequests, } from "../sourceControl/threadPullRequests.ts"; import { PullRequestLinkedThreadsResult, PullRequestOperationError, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ThreadId, type ThreadPullRequestKey, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Schema from "effect/Schema"; @@ -66,3 +72,67 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre }), ), ); + +// Mirrors the rows and filters of `listLinkedPullRequestThreads`. +function linkedKeys(thread: OrchestrationV2AppThread): ReadonlyArray { + if (thread.deletedAt !== null || thread.lineage.sideChat === true) return []; + return visibleThreadPullRequests(thread.pullRequests ?? []) + .map(threadPullRequestKeyOf) + .toSorted(); +} + +function linkedThreadsView( + thread: OrchestrationV2AppThread, + keys: ReadonlyArray, +): string | null { + if (keys.length === 0) return null; + const settled = thread.settledAt !== null || thread.settledOverride === "settled"; + return JSON.stringify([ + keys, + thread.title, + thread.projectId, + thread.archivedAt !== null, + settled, + ]); +} + +/** + * Tells how a domain event changed `pullRequests.linkedThreads` answers, so readers can refresh on + * change instead of polling. `reordered` means activity on a linked thread, or on one whose links + * are unknown since a restart, which can reorder answers. A thread's first full event after a + * restart counts as a change, since its earlier links are unknown. + */ +export function makeLinkedThreadsChangeDetector() { + const views = new Map(); + // Last activity of each thread with visible links. + const activeAt = new Map(); + const active = (threadId: ThreadId, at: DateTime.Utc): boolean => { + const previous = activeAt.get(threadId); + if (previous === undefined) return false; + const millis = DateTime.toEpochMillis(at); + if (millis <= previous) return false; + activeAt.set(threadId, millis); + return true; + }; + return (event: OrchestrationV2DomainEvent): "changed" | "reordered" | null => { + // The projection stamps every non-thread event as the thread's activity. A thread not seen + // since startup may be linked already, since history is not replayed. + if (!event.type.startsWith("thread.")) { + if (!views.has(event.threadId)) return "reordered"; + return active(event.threadId, event.occurredAt) ? "reordered" : null; + } + if (!("lineage" in event.payload)) return null; + const thread = event.payload; + const view = linkedThreadsView(thread, linkedKeys(thread)); + const known = views.has(event.threadId) || event.type === "thread.created"; + const previous = views.get(event.threadId) ?? null; + if (event.type === "thread.deleted") views.delete(event.threadId); + else views.set(event.threadId, view); + if (view === null) activeAt.delete(event.threadId); + if (!known || view !== previous) { + if (view !== null) activeAt.set(event.threadId, DateTime.toEpochMillis(thread.updatedAt)); + return "changed"; + } + return active(event.threadId, thread.updatedAt) ? "reordered" : null; + }; +} diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index bc5b3c5b0861a..918012dadef4e 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -241,6 +241,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( getThreadHistoryPage: () => Effect.die("unused"), getTimelinePage: () => Effect.die("Unused timeline read"), getMessageCount: () => Effect.die("unused message count"), + getMessagesById: () => Effect.die("unused messages by id"), getTurnItem: () => Effect.die("unused turn item read"), getThreadRecords: () => Effect.die("unused record read"), getThreadProjection: unused, @@ -439,7 +440,7 @@ describe("AgentAwarenessRelay", () => { assert.equal(publications.length, 1); assert.isTrue(publications[0]?.url.includes(`/threads/${THREAD_ID}/`) ?? false); assert.equal(publications[0]?.state?.phase, "waiting_for_input"); - }).pipe(Effect.scoped), + }), ); it.effect( @@ -533,7 +534,7 @@ describe("AgentAwarenessRelay", () => { yield* relay.drain; assert.equal(publications.length, 2); assert.equal(publications[1]?.state?.phase, "completed"); - }).pipe(Effect.scoped), + }), ); it.effect("republishes a completed parent for its waiting child after a relink", () => @@ -559,7 +560,7 @@ describe("AgentAwarenessRelay", () => { yield* relay.drain; assert.equal(publications.length, 2); assert.equal(publications[1]?.state?.phase, "waiting_for_approval"); - }).pipe(Effect.scoped), + }), ); it.effect("keeps a child's alert time when the parent's own request comes and goes", () => @@ -727,7 +728,7 @@ describe("AgentAwarenessRelay", () => { yield* relay.drain; assert.equal(publications.length, 3); assert.equal(publications[2]?.state, null); - }).pipe(Effect.scoped), + }), ); it.effect("holds a completion through a continuation gap, then publishes it once", () => @@ -1175,5 +1176,5 @@ it.effect("catches up after startup without polling after success", () => assert.equal(catchUp.activitySnapshotReads, 3); assert.equal(publications.length, 2); assert.equal(publications[1]?.state?.threadId, THREAD_ID); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 73b52571e7416..76f854548deb6 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -117,6 +117,7 @@ function shouldPublishAgentAwarenessEvent( case "thread.active-reordered": case "thread.tags-updated": case "thread.visited": + case "thread.visit-recorded": case "thread.marked-unread": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts index c12e2e44ed7eb..8a3640977ddf2 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts @@ -272,131 +272,127 @@ describe("ResourceTelemetry", () => { ); it.effect("rejects buffered snapshots from an earlier sidecar generation", () => - Effect.scoped( - Effect.gen(function* () { - const startedAt = DateTime.toEpochMillis(yield* DateTime.now); - const stale = nativeSnapshot({ - sequence: 100, - sampledAtUnixMs: startedAt + 1_000, - childCpuTimeMs: 100, - childWriteBytes: 1_000, - }); - const current = nativeSnapshot({ - sequence: 1, - sampledAtUnixMs: startedAt + 2_000, - childCpuTimeMs: 200, - childWriteBytes: 2_000, - }); - const nativeSnapshots = - yield* PubSub.unbounded(); - const layerNative = NativeTelemetryClient.layerTest({ - snapshots: Stream.fromPubSub(nativeSnapshots), - sampleNow: Effect.never, - health: Effect.succeed({ - status: "healthy", - hello: Option.none(), - lastSampleAt: Option.none(), - lastError: Option.none(), - restartCount: 1, - sampleIntervalMs: 1_000, - }), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerNative, - DesktopTelemetryReceiver.layerTest(), - ResourceAttribution.layer, - ), + Effect.gen(function* () { + const startedAt = DateTime.toEpochMillis(yield* DateTime.now); + const stale = nativeSnapshot({ + sequence: 100, + sampledAtUnixMs: startedAt + 1_000, + childCpuTimeMs: 100, + childWriteBytes: 1_000, + }); + const current = nativeSnapshot({ + sequence: 1, + sampledAtUnixMs: startedAt + 2_000, + childCpuTimeMs: 200, + childWriteBytes: 2_000, + }); + const nativeSnapshots = + yield* PubSub.unbounded(); + const layerNative = NativeTelemetryClient.layerTest({ + snapshots: Stream.fromPubSub(nativeSnapshots), + sampleNow: Effect.never, + health: Effect.succeed({ + status: "healthy", + hello: Option.none(), + lastSampleAt: Option.none(), + lastError: Option.none(), + restartCount: 1, + sampleIntervalMs: 1_000, + }), + }); + const layerTelemetry = ResourceTelemetry.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerNative, + DesktopTelemetryReceiver.layerTest(), + ResourceAttribution.layer, ), - ); + ), + ); - yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - const subscription = yield* telemetry.subscribe; - const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild); + yield* Effect.gen(function* () { + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; + const subscription = yield* telemetry.subscribe; + const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild); - yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0)); - yield* Effect.yieldNow; - expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0); + yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0)); + yield* Effect.yieldNow; + expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0); - yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1)); - const received = yield* Fiber.join(nextSnapshot); + yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1)); + const received = yield* Fiber.join(nextSnapshot); - expect(Option.isSome(received)).toBe(true); - expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe( - current.sampledAtUnixMs, - ); - }).pipe(Effect.provide(layerTelemetry)); - }), - ), + expect(Option.isSome(received)).toBe(true); + expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe( + current.sampledAtUnixMs, + ); + }).pipe(Effect.provide(layerTelemetry)); + }), ); it.effect("atomically subscribes while a desktop update is being rebuilt", () => - Effect.scoped( - Effect.gen(function* () { - const startedAt = DateTime.toEpochMillis(yield* DateTime.now); - const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000); - const desktopChanges = yield* PubSub.unbounded(); - const rebuildStarted = yield* Deferred.make(); - const finishRebuild = yield* Deferred.make(); - const attributionReads = yield* Ref.make(0); - const layerAttribution = Layer.succeed( - ResourceAttribution.ResourceAttribution, - ResourceAttribution.ResourceAttribution.of({ - record: () => Effect.void, - snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe( - Effect.flatMap((count) => - count === 1 - ? Effect.void - : Deferred.succeed(rebuildStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishRebuild)), - ), - ), - Effect.andThen( - Effect.succeed({ - readAt: DateTime.makeUnsafe(startedAt), - entries: [], - }), - ), + Effect.gen(function* () { + const startedAt = DateTime.toEpochMillis(yield* DateTime.now); + const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000); + const desktopChanges = yield* PubSub.unbounded(); + const rebuildStarted = yield* Deferred.make(); + const finishRebuild = yield* Deferred.make(); + const attributionReads = yield* Ref.make(0); + const layerAttribution = Layer.succeed( + ResourceAttribution.ResourceAttribution, + ResourceAttribution.ResourceAttribution.of({ + record: () => Effect.void, + snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 + ? Effect.void + : Deferred.succeed(rebuildStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishRebuild)), + ), ), - }), - ); - const layerNative = NativeTelemetryClient.layerTest({ - sampleNow: Effect.never, - health: Effect.succeed({ - status: "healthy", - hello: Option.none(), - lastSampleAt: Option.none(), - lastError: Option.none(), - restartCount: 0, - sampleIntervalMs: 1_000, - }), - }); - const layerDesktop = DesktopTelemetryReceiver.layerTest({ - changes: Stream.fromPubSub(desktopChanges), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)), - ); + Effect.andThen( + Effect.succeed({ + readAt: DateTime.makeUnsafe(startedAt), + entries: [], + }), + ), + ), + }), + ); + const layerNative = NativeTelemetryClient.layerTest({ + sampleNow: Effect.never, + health: Effect.succeed({ + status: "healthy", + hello: Option.none(), + lastSampleAt: Option.none(), + lastError: Option.none(), + restartCount: 0, + sampleIntervalMs: 1_000, + }), + }); + const layerDesktop = DesktopTelemetryReceiver.layerTest({ + changes: Stream.fromPubSub(desktopChanges), + }); + const layerTelemetry = ResourceTelemetry.layer.pipe( + Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)), + ); - yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - yield* Effect.yieldNow; - yield* PubSub.publish(desktopChanges, nextDesktopSnapshot); - yield* Deferred.await(rebuildStarted); + yield* Effect.gen(function* () { + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; + yield* Effect.yieldNow; + yield* PubSub.publish(desktopChanges, nextDesktopSnapshot); + yield* Deferred.await(rebuildStarted); - const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild); - yield* Effect.yieldNow; - yield* Deferred.succeed(finishRebuild, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); + const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild); + yield* Effect.yieldNow; + yield* Deferred.succeed(finishRebuild, undefined); + const subscription = yield* Fiber.join(subscriptionFiber); - expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe( - nextDesktopSnapshot.sampledAtUnixMs, - ); - expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power); - }).pipe(Effect.provide(layerTelemetry)); - }), - ), + expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe( + nextDesktopSnapshot.sampledAtUnixMs, + ); + expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power); + }).pipe(Effect.provide(layerTelemetry)); + }), ); }); diff --git a/apps/server/src/secrets/SecretCheck.test.ts b/apps/server/src/secrets/SecretCheck.test.ts index 9c0bad4cd3111..473cab1dfc65c 100644 --- a/apps/server/src/secrets/SecretCheck.test.ts +++ b/apps/server/src/secrets/SecretCheck.test.ts @@ -228,7 +228,7 @@ it.layer(layerTest)("SecretCheck", (it) => { ]); assert.deepStrictEqual(server.refreshed, [dependent]); assert.deepStrictEqual(yield* server.registry.listUnavailable, []); - }).pipe(Effect.scoped), + }), ); it.effect("an unreadable secret fails naming its provider and leaves instances alone", () => @@ -250,7 +250,7 @@ it.layer(layerTest)("SecretCheck", (it) => { (yield* server.registry.listUnavailable).map((entry) => entry.instanceId), [dependent], ); - }).pipe(Effect.scoped), + }), ); it.effect("a failed check keeps the value the server already holds", () => @@ -267,7 +267,7 @@ it.layer(layerTest)("SecretCheck", (it) => { assert.deepStrictEqual(yield* server.resolver.read([locked]), ["locked-key"]); assert.deepStrictEqual(server.reads.slice(readsBefore), [locked.reference]); - }).pipe(Effect.scoped), + }), ); it.effect("a check applies to an instance whose other secret failed a later refresh", () => @@ -289,7 +289,7 @@ it.layer(layerTest)("SecretCheck", (it) => { secrets: ["wanted-new", "locked-key"], }); assert.deepStrictEqual(yield* server.registry.listUnavailable, []); - }).pipe(Effect.scoped), + }), ); it.effect("a check applies the value it read when a refresh re-reads that secret first", () => @@ -358,6 +358,6 @@ it.layer(layerTest)("SecretCheck", (it) => { assert.deepStrictEqual(server.createdConfigs.at(-1), { keys: { a: "wanted-new", b: "locked-key" }, }); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index a33a750052320..fca8c4bedf084 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -575,6 +575,7 @@ const layerScheduledTaskWebhookOrigin = Layer.effect( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerScheduledTaskWebhookOrigin), Layer.provide(ProviderUsageAnalytics.layer), Layer.provide(layerCheckpointStore), diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index 2bc8f31c8f8b3..563bf47f8ae6f 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -37,166 +37,162 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; it.effect("parks automatic pull until activation without delaying command readiness", () => - Effect.scoped( - Effect.gen(function* () { - const activation = yield* Deferred.make(); - const prepared = yield* Deferred.make(); - const commitTrial = yield* Deferred.make(); - const statusCalled = yield* Deferred.make(); - const statusInterrupted = yield* Deferred.make(); - const cwd = "/auto-pull-project"; - const updatedAt = "2026-01-01T00:00:00.000Z"; - const snapshot = { - projects: [ - { - id: ProjectId.make("auto-pull-project"), - title: "Auto pull project", - workspaceRoot: cwd, - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: updatedAt, - updatedAt, - deletedAt: null, - }, - ], - updatedAt, - }; - const recovery = { - terminalizedRuns: 0, - stoppedSessions: 0, - closedRequests: 0, - retiredEffects: 0, - requeuedEffects: 0, - }; - const importSummary = { importedThreadCount: 0, importedMessageCount: 0 }; - const dependencies: Layer.Layer< - Layer.Services> - > = Layer.mergeAll( - Layer.mock(ServerConfig.ServerConfig)({ - ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe( - Effect.provide(Path.layer), - )), - baseDir: cwd, - logLevel: "Error", - traceMinLevel: "Info", - traceTimingEnabled: false, - traceBatchWindowMs: 200, - traceMaxBytes: 1024, - traceMaxFiles: 1, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpLogsUrl: undefined, - otlpTracesExport: DEFAULT_SIGNAL_EXPORT, - otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, - otlpLogsExport: DEFAULT_SIGNAL_EXPORT, - otelEnvironment: OtelEnvironment.none, - staticDir: undefined, - devAllowedOrigins: [], - desktopBootstrapToken: undefined, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - mode: "desktop", - cwd, - host: "localhost", - port: 3773, - devUrl: undefined, - noBrowser: true, - startupPresentation: "browser", - autoBootstrapProjectFromCwd: false, + Effect.gen(function* () { + const activation = yield* Deferred.make(); + const prepared = yield* Deferred.make(); + const commitTrial = yield* Deferred.make(); + const statusCalled = yield* Deferred.make(); + const statusInterrupted = yield* Deferred.make(); + const cwd = "/auto-pull-project"; + const updatedAt = "2026-01-01T00:00:00.000Z"; + const snapshot = { + projects: [ + { + id: ProjectId.make("auto-pull-project"), + title: "Auto pull project", + workspaceRoot: cwd, + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: updatedAt, + updatedAt, + deletedAt: null, + }, + ], + updatedAt, + }; + const recovery = { + terminalizedRuns: 0, + stoppedSessions: 0, + closedRequests: 0, + retiredEffects: 0, + requeuedEffects: 0, + }; + const importSummary = { importedThreadCount: 0, importedMessageCount: 0 }; + const dependencies: Layer.Layer< + Layer.Services> + > = Layer.mergeAll( + Layer.mock(ServerConfig.ServerConfig)({ + ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe(Effect.provide(Path.layer))), + baseDir: cwd, + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: false, + traceBatchWindowMs: 200, + traceMaxBytes: 1024, + traceMaxFiles: 1, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpLogsUrl: undefined, + otlpTracesExport: DEFAULT_SIGNAL_EXPORT, + otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, + otlpLogsExport: DEFAULT_SIGNAL_EXPORT, + otelEnvironment: OtelEnvironment.none, + staticDir: undefined, + devAllowedOrigins: [], + desktopBootstrapToken: undefined, + logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + mode: "desktop", + cwd, + host: "localhost", + port: 3773, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + autoBootstrapProjectFromCwd: false, + }), + Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), + Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ + pendingThreadCount: Effect.succeed(0), + reconcileShells: Effect.succeed(importSummary), + importPendingTranscripts: Effect.succeed(importSummary), + }), + Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ + recover: Effect.succeed(recovery), + prepareForShutdown: Effect.void, + reconcile: () => Effect.succeed(recovery), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), + Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }), + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), + Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ + publish: (event) => Effect.succeed({ ...event, sequence: 1 }), + }), + Layer.mock(ServerSettings.ServerSettingsService)({ + start: Effect.void, + getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("auto-pull-environment"), + label: "Test environment", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, }), - Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), - Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ - pendingThreadCount: Effect.succeed(0), - reconcileShells: Effect.succeed(importSummary), - importPendingTranscripts: Effect.succeed(importSummary), - }), - Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ - recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, - reconcile: () => Effect.succeed(recovery), - }), - Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), - Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }), - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => Effect.succeed({ ...event, sequence: 1 }), - }), - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }), - }), - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId: EnvironmentId.make("auto-pull-environment"), - label: "Test environment", - platform: { os: "darwin", arch: "arm64" }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }), - }), - Layer.mock(ProjectStore.ProjectStoreV2)({ - listShells: () => Effect.succeed(snapshot.projects), - }), - Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - countThreads: () => Effect.succeed(0), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({}), - Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ - managed: true, - protocol: SERVICE_LAUNCHER_PROTOCOL, - prepareTrial: () => - Deferred.succeed(prepared, undefined).pipe( - Effect.andThen(Deferred.await(commitTrial)), - Effect.as(undefined), - ), - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({ - statusDetails: (root) => - Deferred.succeed(statusCalled, root).pipe( - Effect.andThen(Effect.never), - Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)), - ), - }), - Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }), - // No provider logins or Connect link, so startup records no owners. - FileSystem.layerNoop({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), - NodeCrypto.layer, - Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), - Layer.mock(ExternalLauncher.ExternalLauncher)({}), - Layer.mock(HttpServer.HttpServer)({ - address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), - }), - Path.layer, - ); + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed(snapshot.projects), + }), + Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + countThreads: () => Effect.succeed(0), + }), + Layer.mock(ThreadLaunch.ThreadLaunchService)({}), + Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ + managed: true, + protocol: SERVICE_LAUNCHER_PROTOCOL, + prepareTrial: () => + Deferred.succeed(prepared, undefined).pipe( + Effect.andThen(Deferred.await(commitTrial)), + Effect.as(undefined), + ), + }), + Layer.mock(GitVcsDriver.GitVcsDriver)({ + statusDetails: (root) => + Deferred.succeed(statusCalled, root).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)), + ), + }), + Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }), + // No provider logins or Connect link, so startup records no owners. + FileSystem.layerNoop({}), + Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), + NodeCrypto.layer, + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(HttpServer.HttpServer)({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), + }), + Path.layer, + ); - yield* Effect.gen(function* () { - const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; - yield* startup.markHttpListening; + yield* Effect.gen(function* () { + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + yield* startup.markHttpListening; - yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled)); - expect(yield* Deferred.isDone(activation)).toBe(false); - expect(yield* Deferred.isDone(statusCalled)).toBe(false); - expect(yield* Deferred.isDone(prepared)).toBe(true); + yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled)); + expect(yield* Deferred.isDone(activation)).toBe(false); + expect(yield* Deferred.isDone(statusCalled)).toBe(false); + expect(yield* Deferred.isDone(prepared)).toBe(true); - yield* Deferred.succeed(commitTrial, undefined); - yield* Deferred.await(activation); - expect(yield* Deferred.await(statusCalled)).toBe(cwd); - yield* startup.awaitCommandReady; - }).pipe( - Effect.provide( - ServerRuntimeStartup.layerWithOptions({ - activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid), - awaitAuxiliaryParked: Effect.void, - }).pipe(Layer.provide(dependencies)), - ), - Effect.provideService(ServerActivation, Deferred.await(activation)), - ); - expect(yield* Deferred.isDone(statusInterrupted)).toBe(true); - }), - ), + yield* Deferred.succeed(commitTrial, undefined); + yield* Deferred.await(activation); + expect(yield* Deferred.await(statusCalled)).toBe(cwd); + yield* startup.awaitCommandReady; + }).pipe( + Effect.provide( + ServerRuntimeStartup.layerWithOptions({ + activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid), + awaitAuxiliaryParked: Effect.void, + }).pipe(Layer.provide(dependencies)), + ), + Effect.provideService(ServerActivation, Deferred.await(activation)), + ); + expect(yield* Deferred.isDone(statusInterrupted)).toBe(true); + }), ); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 180defacbfcc6..7a3c6068a0543 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -53,252 +53,242 @@ it.effect.each([ "launch-failure", "project-failure", ] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => - Effect.scoped( - Effect.gen(function* () { - const projectId = ProjectId.make("bootstrap-project"); - const instanceId = ProviderInstanceId.make( - scenario === "disabled-default" ? "custom" : "codex", - ); - const events: ServerLifecycleStreamEvent[] = []; - const recovery = { - terminalizedRuns: 0, - stoppedSessions: 0, - closedRequests: 0, - retiredEffects: 0, - requeuedEffects: 0, - }; - const imports = { importedThreadCount: 0, importedMessageCount: 0 }; - const dependencies = Layer.mergeAll( - NodeCrypto.layer, - Path.layer, - Layer.mock(ServerConfig.ServerConfig)({ - ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( - Effect.provide(Path.layer), - )), - baseDir: "/bootstrap-project", - logLevel: "Error", - traceMinLevel: "Info", - traceTimingEnabled: false, - traceBatchWindowMs: 200, - traceMaxBytes: 1024, - traceMaxFiles: 1, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpLogsUrl: undefined, - otlpTracesExport: DEFAULT_SIGNAL_EXPORT, - otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, - otlpLogsExport: DEFAULT_SIGNAL_EXPORT, - otelEnvironment: OtelEnvironment.none, - staticDir: undefined, - devAllowedOrigins: [], - desktopBootstrapToken: undefined, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - mode: "web", - cwd: "/bootstrap-project", - host: "localhost", - port: 3773, - devUrl: undefined, - noBrowser: true, - startupPresentation: "browser", - autoBootstrapProjectFromCwd: true, - }), - Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), - Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ - pendingThreadCount: Effect.succeed(0), - reconcileShells: Effect.succeed(imports), - importPendingTranscripts: Effect.succeed(imports), - }), - Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ - recover: Effect.succeed(recovery), - prepareForShutdown: Effect.void, - reconcile: () => Effect.succeed(recovery), - }), - Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), - Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }), - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => - Effect.sync(() => { - const published = { ...event, sequence: events.length + 1 }; - events.push(published); - return published; - }), - }), - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - getSettings: Effect.succeed({ - ...DEFAULT_SERVER_SETTINGS, - defaultModelSelection: - scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("codex"), - enabled: false, - config: {}, - }, - }, - }), - }), - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId: EnvironmentId.make("bootstrap-environment"), - label: "Test environment", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, + Effect.gen(function* () { + const projectId = ProjectId.make("bootstrap-project"); + const instanceId = ProviderInstanceId.make( + scenario === "disabled-default" ? "custom" : "codex", + ); + const events: ServerLifecycleStreamEvent[] = []; + const recovery = { + terminalizedRuns: 0, + stoppedSessions: 0, + closedRequests: 0, + retiredEffects: 0, + requeuedEffects: 0, + }; + const imports = { importedThreadCount: 0, importedMessageCount: 0 }; + const dependencies = Layer.mergeAll( + NodeCrypto.layer, + Path.layer, + Layer.mock(ServerConfig.ServerConfig)({ + ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( + Effect.provide(Path.layer), + )), + baseDir: "/bootstrap-project", + logLevel: "Error", + traceMinLevel: "Info", + traceTimingEnabled: false, + traceBatchWindowMs: 200, + traceMaxBytes: 1024, + traceMaxFiles: 1, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpLogsUrl: undefined, + otlpTracesExport: DEFAULT_SIGNAL_EXPORT, + otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, + otlpLogsExport: DEFAULT_SIGNAL_EXPORT, + otelEnvironment: OtelEnvironment.none, + staticDir: undefined, + devAllowedOrigins: [], + desktopBootstrapToken: undefined, + logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + mode: "web", + cwd: "/bootstrap-project", + host: "localhost", + port: 3773, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + autoBootstrapProjectFromCwd: true, + }), + Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), + Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ + pendingThreadCount: Effect.succeed(0), + reconcileShells: Effect.succeed(imports), + importPendingTranscripts: Effect.succeed(imports), + }), + Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ + recover: Effect.succeed(recovery), + prepareForShutdown: Effect.void, + reconcile: () => Effect.succeed(recovery), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), + Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }), + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), + Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ + publish: (event) => + Effect.sync(() => { + const published = { ...event, sequence: events.length + 1 }; + events.push(published); + return published; }), - }), - Layer.mock(ProjectStore.ProjectStoreV2)({}), - Layer.mock(ProjectService.ProjectService)({ - bootstrap: () => - scenario === "project-failure" - ? Effect.die("project bootstrap failed") - : Effect.succeed({ - created: true, - project: { - id: projectId, - title: "Project", - workspaceRoot: "/bootstrap-project", - repositoryIdentity: null, - faviconPath: null, - scripts: [], - createdAt: "2026-01-01T00:00:00Z", - updatedAt: "2026-01-01T00:00:00Z", - deletedAt: null, - defaultModelSelection: - scenario === "disabled-default" - ? { instanceId, model: "custom-model" } - : null, - }, - }), - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - countThreads: () => Effect.succeed(0), - listActiveShellIndex: () => Effect.succeed([]), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({ - launch: (input) => { - assert.equal(input.modelSelection.instanceId, instanceId); - return scenario === "launch-failure" - ? Effect.fail( - new ThreadLaunch.ThreadLaunchError({ - operation: "create-thread", - commandId: CommandId.make("bootstrap-command"), - projectId, - cause: "test launch failure", - }), - ) - : Effect.fail( - new ThreadManagement.ThreadManagementProviderInstanceDisabledError({ - projectId, - instanceId, - }), - ); + }), + Layer.mock(ServerSettings.ServerSettingsService)({ + start: Effect.void, + getSettings: Effect.succeed({ + ...DEFAULT_SERVER_SETTINGS, + defaultModelSelection: + scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("codex"), + enabled: false, + config: {}, + }, }, }), - Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ - managed: false, - protocol: undefined, - prepareTrial: () => Effect.undefined, - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(AnalyticsService.AnalyticsService)({}), - // No provider logins or Connect link, so startup records no owners. - FileSystem.layerNoop({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), - Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), - Layer.mock(ExternalLauncher.ExternalLauncher)({}), - Layer.mock(HttpServer.HttpServer)({ - address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("bootstrap-environment"), + label: "Test environment", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, }), - ); - yield* Effect.gen(function* () { - const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; - yield* startup.markHttpListening; - const ready = yield* Effect.exit(startup.awaitCommandReady); - assert.equal(Exit.isSuccess(ready), scenario !== "project-failure"); - const welcome = events.find((event) => event.type === "welcome"); - if (scenario === "project-failure") { - assert.isUndefined(welcome); - } else { - assert.isDefined(welcome); - if (welcome?.type === "welcome") { - assert.equal(welcome.payload.bootstrapProjectId, projectId); - assert.isUndefined(welcome.payload.bootstrapThreadId); - } + }), + Layer.mock(ProjectStore.ProjectStoreV2)({}), + Layer.mock(ProjectService.ProjectService)({ + bootstrap: () => + scenario === "project-failure" + ? Effect.die("project bootstrap failed") + : Effect.succeed({ + created: true, + project: { + id: projectId, + title: "Project", + workspaceRoot: "/bootstrap-project", + repositoryIdentity: null, + faviconPath: null, + scripts: [], + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + deletedAt: null, + defaultModelSelection: + scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, + }, + }), + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + countThreads: () => Effect.succeed(0), + listActiveShellIndex: () => Effect.succeed([]), + }), + Layer.mock(ThreadLaunch.ThreadLaunchService)({ + launch: (input) => { + assert.equal(input.modelSelection.instanceId, instanceId); + return scenario === "launch-failure" + ? Effect.fail( + new ThreadLaunch.ThreadLaunchError({ + operation: "create-thread", + commandId: CommandId.make("bootstrap-command"), + projectId, + cause: "test launch failure", + }), + ) + : Effect.fail( + new ThreadManagement.ThreadManagementProviderInstanceDisabledError({ + projectId, + instanceId, + }), + ); + }, + }), + Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ + managed: false, + protocol: undefined, + prepareTrial: () => Effect.undefined, + }), + Layer.mock(GitVcsDriver.GitVcsDriver)({}), + Layer.mock(AnalyticsService.AnalyticsService)({}), + // No provider logins or Connect link, so startup records no owners. + FileSystem.layerNoop({}), + Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(HttpServer.HttpServer)({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), + }), + ); + yield* Effect.gen(function* () { + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + yield* startup.markHttpListening; + const ready = yield* Effect.exit(startup.awaitCommandReady); + assert.equal(Exit.isSuccess(ready), scenario !== "project-failure"); + const welcome = events.find((event) => event.type === "welcome"); + if (scenario === "project-failure") { + assert.isUndefined(welcome); + } else { + assert.isDefined(welcome); + if (welcome?.type === "welcome") { + assert.equal(welcome.payload.bootstrapProjectId, projectId); + assert.isUndefined(welcome.payload.bootstrapThreadId); } - }).pipe( - Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), - Effect.provideService(ServerActivation, Effect.never), - ); - }), - ), + } + }).pipe( + Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), + Effect.provideService(ServerActivation, Effect.never), + ); + }), ); it.effect("interrupts the effect worker when awareness relay startup fails", () => - Effect.scoped( - Effect.gen(function* () { - const workerInterrupted = yield* Ref.make(false); - const workerFiberRef = yield* Ref.make | null>(null); + Effect.gen(function* () { + const workerInterrupted = yield* Ref.make(false); + const workerFiberRef = yield* Ref.make | null>(null); - const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({ - runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))), - startRelay: Effect.yieldNow.pipe( - Effect.andThen(Effect.die("awareness relay startup failed")), - ), - workerFiberRef, - }).pipe(Effect.exit); + const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({ + runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))), + startRelay: Effect.yieldNow.pipe( + Effect.andThen(Effect.die("awareness relay startup failed")), + ), + workerFiberRef, + }).pipe(Effect.exit); - assert.isTrue(Exit.isFailure(exit)); - assert.isTrue(yield* Ref.get(workerInterrupted)); - assert.isNull(yield* Ref.get(workerFiberRef)); - }), - ), + assert.isTrue(Exit.isFailure(exit)); + assert.isTrue(yield* Ref.get(workerInterrupted)); + assert.isNull(yield* Ref.get(workerFiberRef)); + }), ); it.effect("queues commands until startup signals readiness", () => - Effect.scoped( - Effect.gen(function* () { - const gate = yield* ServerRuntimeStartup.makeCommandGate; - const count = yield* Ref.make(0); - const queued = yield* gate - .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) - .pipe(Effect.forkScoped); + Effect.gen(function* () { + const gate = yield* ServerRuntimeStartup.makeCommandGate; + const count = yield* Ref.make(0); + const queued = yield* gate + .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) + .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.equal(yield* Ref.get(count), 0); - yield* gate.signalCommandReady; - assert.equal(yield* Fiber.join(queued), 1); - }), - ), + yield* Effect.yieldNow; + assert.equal(yield* Ref.get(count), 0); + yield* gate.signalCommandReady; + assert.equal(yield* Fiber.join(queued), 1); + }), ); it.effect("enqueueCommand fails queued work when readiness fails", () => - Effect.scoped( - Effect.gen(function* () { - const commandGate = yield* ServerRuntimeStartup.makeCommandGate; - const failure = yield* Deferred.make(); + Effect.gen(function* () { + const commandGate = yield* ServerRuntimeStartup.makeCommandGate; + const failure = yield* Deferred.make(); - const queuedCommandFiber = yield* commandGate - .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) - .pipe(Effect.forkScoped); + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) + .pipe(Effect.forkScoped); - yield* commandGate.failCommandReady( - new ServerRuntimeStartup.ServerRuntimeStartupError({ - mode: "web", - host: "127.0.0.1", - port: 3773, - cause: new Error("test startup failure"), - }), - ); + yield* commandGate.failCommandReady( + new ServerRuntimeStartup.ServerRuntimeStartupError({ + mode: "web", + host: "127.0.0.1", + port: 3773, + cause: new Error("test startup failure"), + }), + ); - const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); - assert.equal(error.message, "Server runtime startup failed before command readiness."); - }), - ), + const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); + assert.equal(error.message, "Server runtime startup failed before command readiness."); + }), ); it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () => diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index bd0da06157db6..ac699b9c7d6cb 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -318,6 +318,70 @@ it.layer(NodeServices.layer)("service state persistence", (it) => { }), ); + it.effect( + "repoints the systemd unit the manager loads when environment.d moves XDG_CONFIG_HOME", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-xdg-" }); + const home = path.join(root, "home"); + const managerUnitDir = path.join(home, ".config", "systemd", "user"); + const unitPath = path.join(managerUnitDir, "t3code.service"); + const render = (version: string) => + renderBootServiceUnit({ ...unitPlan(root, version), unitPath }); + yield* fs.makeDirectory(managerUnitDir, { recursive: true }); + yield* fs.writeFileString(unitPath, render("1.0.0")); + // Fake manager: busctl reports the unit search path, systemctl reloads. + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin, { recursive: true }); + const unitPathJson = JSON.stringify({ + type: "as", + data: [`${managerUnitDir}.control`, managerUnitDir, "/usr/lib/systemd/user"], + }); + yield* fs.writeFileString( + path.join(bin, "busctl"), + `#!/bin/sh\nprintf '%s\\n' '${unitPathJson}'\n`, + ); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`, + ); + yield* fs.chmod(path.join(bin, "busctl"), 0o755); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "process.exit(0);\n", + ); + yield* Effect.promise(() => + writeServiceState(path.join(root, "runtime", "service-state.json"), { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + vi.stubEnv("PATH", bin); + vi.stubEnv("HOME", home); + // environment.d changes what services inherit, not where the manager reads units. + vi.stubEnv("XDG_CONFIG_HOME", path.join(home, "service-config")); + vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.service"); + + yield* Effect.promise(() => + expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."), + ); + + assert.equal(yield* fs.readFileString(unitPath), render("1.1.0")); + assert.equal(yield* fs.readFileString(path.join(root, "reloads")), "reload\n"); + }), + ); + it.effect("keeps the service manager's append log bounded when it starts", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -392,6 +456,36 @@ process.exit(0); }), ); + it.effect("starts the runtime in a T3 home whose name ends in a space", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-space-" }); + const root = path.join(parent, "T3 data "); + const versionDir = path.join(root, "runtime", "versions", "1.0.0"); + yield* writeFakeRuntime( + fs, + path, + versionDir, + ` +import { writeFileSync } from "node:fs"; +writeFileSync(new URL("./started", import.meta.url), ""); +process.exit(0); +`, + ); + yield* fs.writeFileString( + path.join(root, "runtime", "service-state.json"), + JSON.stringify({ protocol: 4, activeVersion: "1.0.0" }), + ); + + yield* Effect.promise(() => + expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."), + ); + + assert.isTrue(yield* fs.exists(path.join(versionDir, "started"))); + }), + ); + it.effect("refuses non-install legacy documents without rewriting or spawning", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -1492,6 +1586,56 @@ process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.dat }), ); + it.effect("starts no trial when stopped during the pre-update backup", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-backup-stop-" }); + const statePath = path.join(root, "runtime", "service-state.json"); + const childSource = "setInterval(() => {}, 1000);\n"; + for (const version of ["1.0.0", "1.1.0"]) { + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", version), + childSource, + ); + } + const dbPath = path.join(root, "userdata", "state.sqlite"); + yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); + yield* fs.writeFileString(dbPath, "database"); + const pending = { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.0.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + dbPath, + status: "pending", + }, + } as const; + yield* Effect.promise(() => writeServiceState(statePath, pending)); + const childCount = spawnedChildren.length; + const launcher = new Launcher(root, pending); + + // Recovery is already queued, so this stop lands while the backup runs. + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + // A trial started here arms its 30-minute prepared timer, which keeps the stopped launcher alive. + assert.deepEqual( + spawnedChildren.slice(childCount).map((child) => child.spawnargs.join(" ")), + [], + ); + assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending); + const backupDir = path.join(root, "runtime", "db-backup", "update-1"); + assert.isFalse(yield* fs.exists(backupDir)); + assert.isFalse(yield* fs.exists(`${backupDir}.staging`)); + }), + ); + it.effect("records no update when the server exits during the backup check", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index db245e16485ce..1a6c07cf43659 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -35,6 +35,7 @@ import { SERVICE_RESTART_PENDING_FILE, SERVICE_STOP_MARKER_FILE, SERVICE_UNIT_ENV, + systemdUnitDirectoryOf, } from "./cloud/serviceProtocol.ts"; import { legacyOwnerStartedBeforeRecord, @@ -123,7 +124,34 @@ export async function registerServiceTask( } } -function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined { +// The manager's environment can differ from the one it gives services (environment.d). +async function readSystemdUnitDirectory(): Promise { + try { + const { stdout } = await NodeUtil.promisify(NodeChildProcess.execFile)( + "busctl", + [ + "--user", + "--json=short", + "get-property", + "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", + "org.freedesktop.systemd1.Manager", + "UnitPath", + ], + { timeout: 5_000 }, + ); + const { data } = JSON.parse(stdout) as { readonly data?: unknown }; + return Array.isArray(data) && data.every((entry) => typeof entry === "string") + ? systemdUnitDirectoryOf(data) + : undefined; + } catch { + return undefined; + } +} + +async function serviceUnitFromEnvironment( + env: NodeJS.ProcessEnv = process.env, +): Promise { const unitName = env[SERVICE_UNIT_ENV]?.trim(); if (!unitName) return undefined; if (unitName.endsWith(".xml")) { @@ -141,14 +169,18 @@ function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): Servi reload: () => Promise.resolve(), }; } - // The manager's own environment, which decides where it reads user units. const xdgConfigHome = env.XDG_CONFIG_HOME?.trim(); - const configHome = - xdgConfigHome && NodePath.isAbsolute(xdgConfigHome) - ? xdgConfigHome - : NodePath.join(home, ".config"); + const unitDir = + (await readSystemdUnitDirectory()) ?? + NodePath.join( + xdgConfigHome && NodePath.isAbsolute(xdgConfigHome) + ? xdgConfigHome + : NodePath.join(home, ".config"), + "systemd", + "user", + ); return { - path: NodePath.join(configHome, "systemd", "user", unitName), + path: NodePath.join(unitDir, unitName), reload: () => new Promise((resolve, reject) => { NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], { @@ -294,14 +326,18 @@ async function syncDirectory(directory: string): Promise { } } -function runCp(args: ReadonlyArray): Promise { +function runCp(args: ReadonlyArray, signal?: AbortSignal): Promise { return new Promise((resolve) => { - NodeChildProcess.execFile("cp", args, (error) => resolve(error === null)); + NodeChildProcess.execFile("cp", args, { signal }, (error) => resolve(error === null)); }); } // macOS fs.copyFile clone flags fall back to full copies. -async function copyDatabaseFile(source: string, destination: string): Promise { +async function copyDatabaseFile( + source: string, + destination: string, + signal?: AbortSignal, +): Promise { // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; // cp -c replaces files and breaks hard links; copy into hard-linked destinations instead. @@ -314,7 +350,9 @@ async function copyDatabaseFile(source: string, destination: string): Promise { +async function backupDatabaseOnce( + baseDir: string, + pending: PendingServiceUpdate, + signal: AbortSignal, +): Promise { const backupDir = databaseBackupDir(baseDir, pending.id); if (await pathExists(backupDir)) return; @@ -502,10 +544,11 @@ async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 }); try { for (const suffix of DB_FILE_SUFFIXES) { + signal.throwIfAborted(); const source = `${pending.dbPath}${suffix}`; if (suffix !== "" && !(await pathExists(source))) continue; const destination = databaseBackupFile(stagingDir, suffix); - await copyDatabaseFile(source, destination); + await copyDatabaseFile(source, destination, signal); await syncFile(destination); } await NodeFSP.rename(stagingDir, backupDir); @@ -798,6 +841,7 @@ export class Launcher { #timer: NodeJS.Timeout | undefined; #transitions: Promise = Promise.resolve(); #stopRequested = false; + readonly #stopSignal = new AbortController(); #stopping = false; #done = false; readonly #completion = Promise.withResolvers(); @@ -916,6 +960,7 @@ export class Launcher { return; } this.#stopRequested = true; + this.#stopSignal.abort(); this.#clearTimer(); this.#enqueue(async () => { // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup. @@ -1011,11 +1056,14 @@ export class Launcher { async #startTrial(pending: PendingServiceUpdate): Promise { try { - await backupDatabaseOnce(this.#baseDir, pending); + await backupDatabaseOnce(this.#baseDir, pending, this.#stopSignal.signal); } catch { + // A stop aborts the copy and leaves the update pending for the next start. + if (this.#stopRequested) return; await this.#returnToPrevious(pending, "failed", "db-backup-failed"); return; } + if (this.#stopRequested) return; try { await this.#startChild(pending.targetVersion, "trial", pending); } catch { @@ -1170,8 +1218,6 @@ export class Launcher { this.#child = null; await this.#terminate(child.process); await finishOnlineBackup?.(); - // A stop during a minutes-long copy should not start a trial; restart resumes the pending update. - if (this.#stopRequested) return; await this.#startTrial(pending); } @@ -1375,8 +1421,8 @@ export interface LauncherOptions { } export async function main(options: LauncherOptions = {}): Promise { - const baseDir = (options.baseDir ?? process.env.T3CODE_HOME)?.trim(); - if (baseDir === undefined || baseDir === "") { + const baseDir = options.baseDir ?? process.env.T3CODE_HOME; + if (baseDir === undefined || baseDir.trim() === "") { throw new Error("T3CODE_HOME is required by the T3 Code service launcher."); } const output = @@ -1403,7 +1449,7 @@ export async function main(options: LauncherOptions = {}): Promise { throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`); } } - const serviceUnit = serviceUnitFromEnvironment(managerEnvironment); + const serviceUnit = await serviceUnitFromEnvironment(managerEnvironment); const logPath = await serviceLogPath(options, serviceUnit); if (logPath !== undefined) { await boundServiceLog(logPath); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index c532d93e81ad9..9d472fe6e77c9 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -283,7 +283,7 @@ it.effect( url, ); } - }).pipe(Effect.scoped), + }), ); it.effect("does not refine a context whose server address is empty", () => diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index d86f77fbdbd83..07f2fe6b99d5d 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -269,7 +269,7 @@ effectIt.effect( handler(new Request("http://localhost/api/voice/models"), context), ); expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone"); - }).pipe(Effect.scoped), + }), ); effectIt.effect.each([ @@ -361,5 +361,5 @@ effectIt.effect.each([ code: "invalid_request", reason, }); - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/speech/native.test.ts b/apps/server/src/speech/native.test.ts index 8712c63ed347d..a41f917b2a682 100644 --- a/apps/server/src/speech/native.test.ts +++ b/apps/server/src/speech/native.test.ts @@ -1,4 +1,8 @@ // @effect-diagnostics nodeBuiltinImport:off - verifies isolated native worker processes and their exit events. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + import { expect, it } from "vite-plus/test"; import { loadNativeSpeechModel } from "./native.ts"; @@ -155,6 +159,37 @@ it("kills a hung streaming feed without waiting for native cleanup", async () => await model.dispose(); await rejected; }); + +it("skips process exit teardown when the backend dies during native inference", async () => { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-speech-orphan-")); + const marker = NodePath.join(directory, "exit-teardown"); + // The exit hook stands in for native atexit teardown; the interval for the threadpool call. + const model = await loadNativeSpeechModel( + "unused.gguf", + new AbortController().signal, + streamingFixture(`async () => { + const { writeFileSync } = process.getBuiltinModule("node:fs"); + process.once("exit", () => writeFileSync(${JSON.stringify(marker)}, "ran")); + setInterval(() => {}, 1 << 30); + process.disconnect(); + return await new Promise(() => {}); + }`), + ); + try { + await model.begin({ timestamps: "none" }, false); + await expect(model.feed(new Float32Array(512).fill(0.25))).rejects.toThrow( + "Speech process exited", + ); + expect( + NodeFS.existsSync(marker), + "orphaned worker ran exit teardown while native inference was in flight", + ).toBe(false); + } finally { + await model.dispose(); + NodeFS.rmSync(directory, { recursive: true, force: true }); + } +}); + const vadFixture = ({ streaming = false, failVad = false, diff --git a/apps/server/src/speech/native.ts b/apps/server/src/speech/native.ts index 8331e1b5e0ec1..70c5d21c6038d 100644 --- a/apps/server/src/speech/native.ts +++ b/apps/server/src/speech/native.ts @@ -182,7 +182,8 @@ process.on("message", async (message) => { error: error instanceof Error ? error.stack ?? error.message : String(error) }); } }); -process.on("disconnect", () => process.exit(0)); +// Exit teardown under in-flight native inference segfaults, so terminate without it. +process.on("disconnect", () => process.kill(process.pid, "SIGKILL")); `; type Reply = { diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 1bbaa450636e2..b0641a20428ec 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -610,7 +610,7 @@ const runCleanupTest = ( | Path.Path | Scope.Scope >, -) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped); +) => effect.pipe(Effect.provide(cleanupTestLayer)); it.live.each(["repository", "uppercase", "bare"] as const)( "keeps a worktree holding an ignored nested %s", @@ -1005,10 +1005,10 @@ describe("subagent worktree ownership", () => { ? "Thread is running or has pending work" : "Not settled", }); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); - it.live.each([ + it.effect.each([ "parent-unsettled", "parent-resettled", "child-unsettled", @@ -1017,6 +1017,7 @@ describe("subagent worktree ownership", () => { ] as const)("cancels inherited settlement during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0, @@ -1209,10 +1210,56 @@ describe("subagent worktree ownership", () => { ? "Settled moments ago" : "Not settled", }); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); - it.live.each([ + it.effect("keeps a checkout two top-level threads store through a symlinked parent", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 8, + }); + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; + fixture.setThreads([ + shell({ ...settled, worktreePath: fixture.worktree }), + shell({ ...settled, id: ThreadId.make("other"), worktreePath: `${linkedParent}/feature` }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), + ]); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }).pipe(Effect.provide(cleanupTestLayer)), + ); + + it.effect("keeps a checkout two top-level threads store in different case on Windows", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 8, + }).pipe(Effect.provideService(HostProcess.Platform, "win32")); + const settled = { branch: "feature", settledAt: at(-20 * DAY_MS) }; + fixture.setThreads([ + shell({ ...settled, worktreePath: fixture.worktree }), + shell({ + ...settled, + id: ThreadId.make("other"), + worktreePath: fixture.worktree.toUpperCase(), + }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }), + ]); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }).pipe(Effect.provide(cleanupTestLayer)), + ); + + it.effect.each([ "running", "pending", "activity", @@ -1224,6 +1271,7 @@ describe("subagent worktree ownership", () => { ] as const)("cancels removal when a child changes during measurement (%s)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const root = shell({ branch: "feature", worktreePath: fixture.worktree }); const child = { @@ -1313,7 +1361,7 @@ describe("deleted thread worktrees", () => { reason: "Thread was deleted", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("applies the remaining subagent's rules when deletion cleanup is off", () => @@ -1335,7 +1383,7 @@ describe("deleted thread worktrees", () => { reason: "Inactive for 30 days", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); // Releases one stopped-session event after the startup sweep and returns the snapshot reads it caused. @@ -1394,7 +1442,7 @@ describe("deleted thread worktrees", () => { const fixture = yield* cleanupFixture(); const reads = yield* stopSessionAfterStartupSweep(fixture, ThreadId.make("thread-1")); expect(reads, "a live thread's stopped session re-read every thread").toBe(0); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once its session stops", () => @@ -1416,7 +1464,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("removes a deleted thread's worktree once a live thread's session in it stops", () => @@ -1446,7 +1494,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1492,7 +1540,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1525,7 +1573,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBeGreaterThan(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("does not sweep for a kept deleted worktree when a session elsewhere stops", () => @@ -1547,7 +1595,7 @@ describe("deleted thread worktrees", () => { ); expect(reads).toBe(0); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1577,7 +1625,7 @@ describe("deleted thread worktrees", () => { fixture.repo, ); expect(reads).toBe(0); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect( @@ -1651,7 +1699,7 @@ describe("deleted thread worktrees", () => { yield* Deferred.await(delivered); yield* fixture.service.drain; expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); it.effect("waits out the settle grace of a subagent that just settled", () => @@ -1672,7 +1720,7 @@ describe("deleted thread worktrees", () => { reason: "Settled moments ago", }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + }).pipe(Effect.provide(cleanupTestLayer)), ); }); @@ -2284,6 +2332,24 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect("keeps a thread's worktree folder that lost its .git link", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), + ]); + yield* fixture.fs.remove(`${fixture.worktree}/.git`); + yield* fixture.fs.makeDirectory(`${fixture.worktree}/node_modules`); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ path: fixture.worktree, outcome: "kept" }), + ]); + expect(yield* fixture.fs.exists(`${fixture.worktree}/node_modules`)).toBe(true); + }), + ), + ); it.live("skips a stored worktree path whose parent is a regular file", () => runCleanupTest( Effect.gen(function* () { @@ -2299,18 +2365,30 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each(["before-check", "while-measuring"] as const)( - "keeps a worktree protected by a missing project root (%s)", - (timing) => + it.live.each([ + ["before-check", "stored"], + ["while-measuring", "stored"], + ["before-check", "symlinked parent"], + ["while-measuring", "symlinked parent"], + ] as const)( + "keeps a worktree protected by a missing project root (%s, %s spelling)", + ([timing, spelling]) => runCleanupTest( Effect.gen(function* () { const fixture = yield* pausedMeasurementFixture(); + let worktree = fixture.worktree; + if (spelling === "symlinked parent") { + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + worktree = `${linkedParent}/feature`; + fixture.setThreads([shell({ branch: "feature", worktreePath: worktree })]); + } if (timing === "before-check") - fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]); + fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); if (timing === "while-measuring") { yield* Deferred.await(fixture.measuring); - fixture.setProjectRoots([fixture.repo, `${fixture.worktree}/removed-checkout`]); + fixture.setProjectRoots([fixture.repo, `${worktree}/removed-checkout`]); } yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(cleanup); @@ -2444,12 +2522,13 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each([ + it.effect.each([ { days: 8, reason: "Inactive for 1 of 8 days" }, { days: null, reason: "No rules apply" }, ])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: days, @@ -2459,9 +2538,7 @@ describe("storage cleanup reports and local file policies", () => { shell({ branch: "feature", worktreePath: fixture.worktree, - latestUserMessageAt: DateTime.makeUnsafe( - DateTime.toEpochMillis(yield* DateTime.now) - DAY_MS, - ), + latestUserMessageAt: at(-DAY_MS), }), ]); yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n"); @@ -2527,7 +2604,7 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each([ + it.effect.each([ [ "its owner's branch is cleared", (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })], @@ -2564,6 +2641,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const { fs, worktree } = fixture; fixture.setPolicy("tracked-changes"); @@ -2615,6 +2693,23 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps a worktree for a live session in a missing folder under its stored alias", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const linkedParent = `${yield* fixture.fs.makeTempDirectoryScoped({ prefix: "cleanup-link-" })}/worktrees`; + yield* fixture.fs.symlink(fixture.config.worktreesDir, linkedParent); + fixture.setThreads([shell({ branch: "feature", worktreePath: `${linkedParent}/feature` })]); + fixture.setOpenSessionCwd(`${linkedParent}/feature/removed-folder`); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Provider session is still open", + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }), + ), + ); it.live("compares the checked-out branch without a full status", () => runCleanupTest( Effect.gen(function* () { @@ -2694,7 +2789,7 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live.each([ + it.effect.each([ ["unchanged", "removed", "No commits beyond the project branch"], ["unmerged", "kept", "Has commits beyond the project branch"], ["detached", "kept", "Project branch is unavailable"], @@ -2702,6 +2797,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("cleans archived local-only worktrees: %s", ([state, outcome, reason]) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: state !== "merged-only", @@ -2724,15 +2820,55 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps an unsettled new thread's unchanged worktree after its first turn", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, setThreads } = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 11, + worktreeOnMerge: true, + worktreeUnchanged: true, + }); + const now = yield* DateTime.now; + const minutesAgo = (minutes: number) => DateTime.subtract(now, { minutes }); + const thread = shell({ + branch: "feature", + worktreePath: worktree, + status: "completed", + createdAt: minutesAgo(40), + latestUserMessageAt: minutesAgo(40), + latestRunRequestedAt: minutesAgo(40), + latestRunStartedAt: minutesAgo(40), + latestRunCompletedAt: minutesAgo(20), + updatedAt: minutesAgo(20), + }); + setThreads([thread]); + + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ outcome: "kept" }); + expect(yield* fs.exists(worktree)).toBe(true); + + setThreads([{ ...thread, settledAt: minutesAgo(10), updatedAt: minutesAgo(10) }]); + const settled = yield* service.runNow; + expect(settled.entries[0]).toMatchObject({ + outcome: "removed", + reason: "No commits beyond the project branch", + }); + }), + ), + ); it.live( "discovers trunk without a remote HEAD or tracking ref and removes an integrated worktree", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([ + shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), + ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -2754,10 +2890,13 @@ describe("storage cleanup reports and local file policies", () => { () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([ + shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) }), + ]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -2782,10 +2921,11 @@ describe("storage cleanup reports and local file policies", () => { it.live("keeps the worktree when the remote default is unavailable even if main exists", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({ ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeUnchanged: true, }); + setThreads([shell({ branch: "feature", worktreePath: worktree, archivedAt: at(-DAY_MS) })]); const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); yield* command(remote, ["init", "--bare", "-b", "trunk"]); yield* command(repo, ["remote", "add", "origin", remote]); @@ -3091,11 +3231,12 @@ describe("storage cleanup reports and local file policies", () => { }); describe("settled worktree rechecks", () => { - it.live.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( + it.effect.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)( "keeps a usage-limited checkout when %s is enabled during measurement", (preference) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); fixture.setSettings({ autoResumeLimitedThreads: false, snoozeLimitedThreads: false }); fixture.setThreads([ @@ -3113,16 +3254,20 @@ describe("settled worktree rechecks", () => { fixture.setSettings({ [preference]: true }); yield* Deferred.succeed(fixture.resume, undefined); const report = yield* Fiber.join(run); - expect(report.entries[0]?.outcome).toBe("kept"); + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Settings changed since check", + }); expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); }), ), ); - it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( + it.effect.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( "keeps a checkout changed during measurement (%j)", (change) => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* pausedMeasurementFixture(); const thread = shell({ branch: "feature", @@ -3150,9 +3295,10 @@ describe("settled worktree rechecks", () => { ); }); -it.live("keeps saved usage data when removing a settled checkout", () => +it.effect("keeps saved usage data when removing a settled checkout", () => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); fixture.setSettings({ storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 }, diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 6c2935d1c59d8..99097501d49d7 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -346,20 +346,6 @@ const make = Effect.gen(function* () { !path.isAbsolute(relative) ); }; - const hasTerminal = (worktreePath: string) => - [...liveTerminals.values()] - .flatMap((entries) => [...entries.values()]) - .some((terminal) => { - if (terminal.status !== "starting" && terminal.status !== "running") return false; - const cwd = path.resolve(terminal.cwd); - return ( - (terminal.worktreePath !== null && - pathKey(terminal.worktreePath) === pathKey(worktreePath)) || - pathKey(cwd) === pathKey(worktreePath) || - inside(worktreePath, cwd) - ); - }); - // pnpm imports packages by clone or reflink when its store shares a device // with the worktree. Those files have one link but share blocks with the // store, so removing them frees almost nothing. A store on another device @@ -500,18 +486,21 @@ const make = Effect.gen(function* () { }); const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* ( - worktreePath: string, + worktreePaths: ReadonlyArray, projects: ReadonlyArray<{ readonly workspaceRoot: string }>, ) { + const contains = (projectPath: string) => + worktreePaths.some( + (worktreePath) => + pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath), + ); for (const project of projects) { const projectPath = path.resolve(project.workspaceRoot); - if (pathKey(projectPath) === pathKey(worktreePath) || inside(worktreePath, projectPath)) - return true; + if (contains(projectPath)) return true; const realPath = yield* fs .realPath(projectPath) .pipe(Effect.orElseSucceed(() => projectPath)); - if (pathKey(realPath) === pathKey(worktreePath) || inside(worktreePath, realPath)) - return true; + if (contains(realPath)) return true; } return false; }); @@ -1021,8 +1010,10 @@ const make = Effect.gen(function* () { return "worktree is a symbolic link"; if (!roots.some((root) => inside(root, realPath))) return "outside the managed worktree folder"; - if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") - return "not a linked worktree"; + const gitLink = yield* fs + .stat(path.join(worktreePath, ".git")) + .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined)); + if (gitLink?.type !== "File") return "not a linked worktree"; return null; }); const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>` @@ -1040,20 +1031,58 @@ const make = Effect.gen(function* () { const threadsById = new Map(snapshot.threads.map((thread) => [thread.id, thread])); const refreshedDefaultRefs = new Map>(); const defaultBranches = new Map(); - const groups = Map.groupBy( - snapshot.threads.filter((thread) => thread.worktreePath !== null), - (thread) => path.resolve(thread.worktreePath!), + // Threads may store one checkout through different symlinked spellings; compare real paths. + // Keys are only compared, never opened, so they take pathKey's Windows case folding. + const canonicalPaths = new Map(); + const canonical = Effect.fnUntraced(function* (target: string) { + const resolved = path.resolve(target); + const cached = canonicalPaths.get(resolved); + if (cached !== undefined) return cached; + const realPath = yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)); + const key = pathKey(realPath); + canonicalPaths.set(resolved, key); + return key; + }); + // A cwd in a deleted folder cannot be resolved, so stored spellings are compared too. + const occupies = Effect.fnUntraced(function* ( + worktreePaths: ReadonlyArray, + target: string, + ) { + const targets = [path.resolve(target), yield* canonical(target)]; + return worktreePaths.some((worktree) => + targets.some((cwd) => pathKey(cwd) === pathKey(worktree) || inside(worktree, cwd)), + ); + }); + const hasTerminal = Effect.fnUntraced(function* (worktreePaths: ReadonlyArray) { + for (const terminal of [...liveTerminals.values()].flatMap((entries) => [ + ...entries.values(), + ])) { + if (terminal.status !== "starting" && terminal.status !== "running") continue; + if ( + (terminal.worktreePath !== null && + (yield* occupies(worktreePaths, terminal.worktreePath))) || + (yield* occupies(worktreePaths, terminal.cwd)) + ) + return true; + } + return false; + }); + const liveThreads = snapshot.threads.filter((thread) => thread.worktreePath !== null); + const liveKeys = yield* Effect.forEach(liveThreads, (thread) => + canonical(thread.worktreePath!), ); - const deletedByPath = Map.groupBy(deletedThreads, (thread) => - path.resolve(thread.worktreePath!), + const groups = Map.groupBy(liveThreads, (_thread, index) => liveKeys[index]!); + const deletedKeys = yield* Effect.forEach(deletedThreads, (thread) => + canonical(thread.worktreePath!), ); + const deletedByPath = Map.groupBy(deletedThreads, (_thread, index) => deletedKeys[index]!); const candidates = [ ...[...groups].map( - ([worktreePath, group]) => + ([worktreeKey, group]) => // A deleted thread still owns the worktree its remaining subagents share, // but only deletion cleanup acts on it; otherwise the live rules apply. deletedByPath - .get(worktreePath) + .get(worktreeKey) ?.find( (deleted) => resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete && @@ -1062,13 +1091,15 @@ const make = Effect.gen(function* () { worktreeOwner(group) ?? group[0]!, ), - ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))), + ...deletedThreads.filter((_thread, index) => !groups.has(deletedKeys[index]!)), ]; for (const thread of candidates) { const settings = resolveWorktreeCleanup(serverSettings, thread.projectId); if (!worktreeCleanupEnabled(settings)) continue; const worktreePath = path.resolve(thread.worktreePath!); - const group = groups.get(worktreePath) ?? []; + const worktreeKey = yield* canonical(worktreePath); + const worktreePaths = [worktreePath, worktreeKey]; + const group = groups.get(worktreeKey) ?? []; const activityAt = Math.max(...group.map(storageCleanupActivityAt)); const deleted = "workspaceRoot" in thread; const settlementChain = deleted @@ -1122,7 +1153,7 @@ const make = Effect.gen(function* () { return keep(waitForStop("thread is running or has pending work")); if (group.some((member) => member.branch !== thread.branch)) return keep("a subagent thread's branch differs from this worktree's branch"); - if (hasTerminal(worktreePath)) return keep(waitForStop("open terminal")); + if (yield* hasTerminal(worktreePaths)) return keep(waitForStop("open terminal")); if ( [...group, ...settlementChain.slice(1)].some( (member) => @@ -1145,6 +1176,9 @@ const make = Effect.gen(function* () { settledFor !== null && settings.worktreeSettledAfterDays !== null && settledFor >= settings.worktreeSettledAfterDays * DAY_MS; + // A worktree is unchanged before its first commit, so only finished threads qualify. + const unchangedApplies = + settings.worktreeUnchanged && (settledThread !== undefined || thread.archivedAt !== null); let eligible = deleted || old || settled; let removalReason = deleted ? "thread was deleted" @@ -1160,15 +1194,16 @@ const make = Effect.gen(function* () { : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days` : settings.worktreeOnMerge ? "not merged" - : settings.worktreeUnchanged + : unchangedApplies ? "has commits beyond the default branch" - : "no rules apply"; + : settings.worktreeUnchanged + ? "not settled" + : "no rules apply"; // Only Git-based rules can make a not-yet-due worktree eligible, so skip Git otherwise. - if (!eligible && !settings.worktreeUnchanged && !settings.worktreeOnMerge) - return keep(notDueReason); + if (!eligible && !unchangedApplies && !settings.worktreeOnMerge) return keep(notDueReason); const pathReason = yield* worktreePathReason(worktreePath); if (pathReason !== null) return keep(pathReason); - if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) + if (yield* containsProjectRoot(worktreePaths, [project, ...snapshot.projects])) return keep("contains a project checkout"); if (yield* branchChanged(worktreePath, thread.branch)) return keep("repository or branch changed"); @@ -1189,8 +1224,12 @@ const make = Effect.gen(function* () { let branch: string | null | undefined; let defaultRef: string; if (remote === null) { - if (!settings.worktreeUnchanged) - return keep("no remote is configured for merged-worktree cleanup"); + if (!unchangedApplies) + return keep( + settings.worktreeUnchanged + ? notDueReason + : "no remote is configured for merged-worktree cleanup", + ); const projectHead = yield* git.execute({ operation: "StorageCleanup.resolveProjectBranch", cwd: repositoryCwd, @@ -1249,7 +1288,7 @@ const make = Effect.gen(function* () { allowNonZeroExit: true, }); const integrated = ancestor.exitCode === 0; - eligible = integrated && settings.worktreeUnchanged; + eligible = integrated && unchangedApplies; if (eligible) removalReason = remote === null @@ -1268,18 +1307,21 @@ const make = Effect.gen(function* () { }); if (eligible) removalReason = "pull request was merged"; } - if (!eligible && remote === null) return keep("has commits beyond the project branch"); + if (!eligible && remote === null) + return keep(integrated ? notDueReason : "has commits beyond the project branch"); } if (!eligible) return keep(notDueReason); // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. const blockedSinceCheck = Effect.fnUntraced(function* () { const latestProjects = yield* projectStore.listShells(); - if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects])) + if (yield* containsProjectRoot(worktreePaths, [project, ...latestProjects])) return "contains a project checkout"; - const latest = (yield* projections.getThreadWorktreePaths({ - includeArchived: true, - })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath); - if (hasTerminal(worktreePath)) return waitForStop("open terminal"); + const bindings = yield* projections.getThreadWorktreePaths({ includeArchived: true }); + const bindingKeys = yield* Effect.forEach(bindings, (binding) => + canonical(binding.worktreePath), + ); + const latest = bindings.filter((_binding, index) => bindingKeys[index] === worktreeKey); + if (yield* hasTerminal(worktreePaths)) return waitForStop("open terminal"); if (deleted) { if ( !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) @@ -1300,12 +1342,15 @@ const make = Effect.gen(function* () { projections.getThreadShell(entry.threadId), ); const latestGroup = latestShells.filter((shell) => shell !== null); + const latestKeys = yield* Effect.forEach(latestGroup, (shell) => + shell.worktreePath === null ? Effect.succeed(null) : canonical(shell.worktreePath), + ); const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); if ( latestGroup.length !== group.length || latestOwner?.id !== thread.id || latestOwner?.branch !== thread.branch || - latestGroup.some((shell) => { + latestGroup.some((shell, index) => { const previous = group.find((member) => member.id === shell.id); return ( previous === undefined || @@ -1313,7 +1358,7 @@ const make = Effect.gen(function* () { !Equal.equals(shell.settledAt, previous.settledAt) || (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || !storageCleanupThreadIdle(shell, now, serverSettings) || - path.resolve(shell.worktreePath!) !== worktreePath || + latestKeys[index] !== worktreeKey || storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) ); }) @@ -1350,9 +1395,8 @@ const make = Effect.gen(function* () { ); // Ready persisted sessions may have released their runtime; only live sessions protect the path. for (const session of sessions) { - const cwd = path.resolve(session.cwd); if ( - (pathKey(cwd) === pathKey(worktreePath) || inside(worktreePath, cwd)) && + (yield* occupies(worktreePaths, session.cwd)) && (yield* providerSessions.isLive(session.id)) ) return waitForStop("provider session is still open"); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 752c19171833e..7fd4b10bc166e 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1399,9 +1399,11 @@ it.layer( process.emitData("prompt "); process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u"); - process.emitData("\u001b[=c\u001b[=0c"); + process.emitData("\u001b[=c\u001b[=0c\u001bZ"); process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\"); process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\"); + // BEL is DCS payload, not a terminator: only ST ends the string. + process.emitData("\u001bP$qm\u0007hidden\u001b\\\u001bP+q544e\u0007hidden\u001b\\"); process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); process.emitData("\u001b]0;x\u001b\u001b[?2026$p"); process.emitData("done\n"); @@ -1417,6 +1419,28 @@ it.layer( }), ); + // Ghostty executes 0x00-0x0F inside a CSI and ignores DEL and 0x10-0x1F; none change the query. + it.effect.each([ + { name: "NUL in DA", data: "A\u001b[0\u0000cB", history: "AB" }, + { name: "DEL in DA", data: "A\u001b[0\u007fcB", history: "AB" }, + { name: "NUL in DECRQM", data: "A\u001b[?2026\u0000$pB", history: "AB" }, + { name: "CR in DSR", data: "AB\u001b[5\rnC", history: "AB\rC" }, + { name: "DLE in DSR", data: "AB\u001b[5\u0010nC", history: "ABC" }, + ])( + "strips a query with an embedded control but keeps what the terminal ran ($name)", + ({ data, history }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + ptyAdapter.processes[0]!.emitData(data); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + const restored = reopened.history.replaceAll("\u0000", ""); + expect(restored.split("\u001b[?1049h")[0]).toBe(history); + }), + ); + it.effect.each([ { name: "OSC", sequence: "\u001b]0;unfinished" }, { name: "DCS", sequence: "\u001bPunfinished" }, @@ -1468,6 +1492,21 @@ it.layer( }), ); + it.effect("keeps a decoded U+009C inside a stripped OSC query out of history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + // libghostty receives UTF-8 (c2 9c), which is OSC payload; only ESC \ ends this string. + process.emitData("A\u001b]11;?\u009cHIDDEN\u001b\\B\n"); + // A DCS string does end at U+009C there, so the text after it stays visible. + process.emitData("C\u001bP$qm\u009cSHOWN\u001b\\D\n"); + yield* manager.close({ threadId: "thread-1" }); + + expect((yield* manager.open(openInput())).history).toMatch(/^AB\nCSHOWN\u001b\\D\n/); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); @@ -2479,7 +2518,7 @@ it.layer( { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } }, ]); expect(ptyAdapter.processes).toHaveLength(1); - }).pipe(Effect.scoped), + }), ); it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () => @@ -2553,7 +2592,7 @@ it.layer( ptyAdapter.processes.at(-1)!.emitData("new session only\n"); expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]); expect(ptyAdapter.spawnInputs).toHaveLength(4); - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -2600,7 +2639,7 @@ it.layer( yield* Deferred.await(restored); expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 }); - }).pipe(Effect.scoped), + }), ); it.effect("sends bounded attach streams only the history the client retains", () => @@ -2651,7 +2690,7 @@ it.layer( expect(yield* full).toEqual(yield* bounded); yield* manager.attachStream({ ...openInput(), restartIfNotRunning: true }, () => Effect.void); yield* expectRetained(); - }).pipe(Effect.scoped), + }), ); it.effect("does not replay in-flight output already included in an observer snapshot", () => @@ -2688,7 +2727,7 @@ it.layer( expect(observed.filter((event) => event.type === "output")).toMatchObject([ { data: "after\n" }, ]); - }).pipe(Effect.scoped), + }), ); it.effect("observes terminal history and live output without changing the process", () => diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 97addc8561221..382d4c94e0f6e 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1197,10 +1197,12 @@ function stripStringTerminator(value: string): string { return value; } -function findStringTerminatorIndex(input: string, start: number): number | null { +// BEL ends only OSC; inside DCS, PM and APC it is payload. A decoded U+009C is the +// reverse: libghostty keeps it inside OSC but ends the other strings there. +function findStringTerminatorIndex(input: string, start: number, isOsc: boolean): number | null { for (let index = start; index < input.length; index += 1) { const codePoint = input.charCodeAt(index); - if (codePoint === 0x07 || codePoint === 0x9c || isControlSequenceCancel(codePoint)) { + if ((isOsc ? codePoint === 0x07 : codePoint === 0x9c) || isControlSequenceCancel(codePoint)) { return index + 1; } // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence. @@ -1268,17 +1270,30 @@ function sanitizeTerminalHistoryChunk( if (nextCodePoint === 0x5b) { let cursor = index + 2; + // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would + // print in ground state. None join the parameters; only executed ones survive a strip. + let body = ""; + let executedControls = ""; while (cursor < input.length) { - const cancelled = isControlSequenceCancel(input.charCodeAt(cursor)); - if (cancelled || isCsiFinalByte(input.charCodeAt(cursor))) { - const sequence = input.slice(index, cursor + 1); - const body = input.slice(index + 2, cursor); + const cursorCodePoint = input.charCodeAt(cursor); + const cancelled = isControlSequenceCancel(cursorCodePoint); + if (cancelled || isCsiFinalByte(cursorCodePoint)) { if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { - append(sequence); + append(input.slice(index, cursor + 1)); + } else { + append(executedControls); } index = cursor + 1; break; } + if (cursorCodePoint < 0x10) { + executedControls += input[cursor]; + } else if ( + (cursorCodePoint >= 0x20 || cursorCodePoint === 0x1b) && + cursorCodePoint !== 0x7f + ) { + body += input[cursor]; + } cursor += 1; } if (cursor >= input.length) { @@ -1296,6 +1311,7 @@ function sanitizeTerminalHistoryChunk( const terminatorIndex = findStringTerminatorIndex( input, Math.max(index + 2, pendingScanStart), + nextCodePoint === 0x5d, ); if (terminatorIndex === null) { return { visibleText, pendingControlSequence: input.slice(index) }; @@ -1316,7 +1332,10 @@ function sanitizeTerminalHistoryChunk( if (escapeSequenceEndIndex === null) { return { visibleText, pendingControlSequence: input.slice(index) }; } - append(input.slice(index, escapeSequenceEndIndex)); + // ESC Z (DECID) is the legacy primary device attributes query. + if (nextCodePoint !== 0x5a) { + append(input.slice(index, escapeSequenceEndIndex)); + } index = escapeSequenceEndIndex; continue; } diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index 48cb40e09d978..6d851b93d374d 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -101,7 +101,7 @@ describe("terminal output window", () => { assert.equal(yield* Queue.size(responses), 0); yield* write(0, { _tag: "Interrupt", requestId: "1" }); assert.equal((yield* Queue.take(responses))._tag, "Exit"); - }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), + }).pipe(Effect.provide(RpcSerialization.layerJson)), ); }); @@ -261,7 +261,7 @@ describe("terminal output stream", () => { assert.deepEqual(yield* takeChunk(healthy), [after]); assert.deepEqual(yield* takeChunk(stalled), [after]); assert.equal(yield* Queue.size(stalled), 0); - }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), + }).pipe(Effect.provide(RpcSerialization.layerJson)), ); it.effect("interrupts recovery while its subscription is still waiting", () => @@ -290,7 +290,7 @@ describe("terminal output stream", () => { yield* Fiber.interrupt(recovery); yield* Deferred.await(interrupted); assert.equal(publisher.listeners.size, 0); - }).pipe(Effect.scoped), + }), ); it.effect("cleans listeners when cancelled during a successful acquisition handoff", () => @@ -324,7 +324,7 @@ describe("terminal output stream", () => { yield* Fiber.join(cancellation); assert.equal(publisher.listeners.size, 0); } - }).pipe(Effect.scoped), + }), ); it.effect("caps each delivered batch at the output window in UTF-8 bytes", () => @@ -349,7 +349,7 @@ describe("terminal output stream", () => { delivered += batch.length; } assert.equal(delivered, 1024); - }).pipe(Effect.scoped), + }), ); it.effect("charges snapshot history but never overflows on one snapshot", () => @@ -367,6 +367,6 @@ describe("terminal output stream", () => { assert.equal(publisher.listeners.size, 1); yield* publisher.publish(snapshot(history)); assert.equal(publisher.listeners.size, 0); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts index 5cb6a1f8d4d8b..783417693c722 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts @@ -343,7 +343,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { { type: "text", text: expect.stringContaining("+handleRemoteCallback()") }, ]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["tool_call", "tool_call_update"] as const)( @@ -362,7 +362,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toContain("tool work"); expect(fixture.state.cancellations).toBe(1); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("rejects native permission and choice requests instead of answering them", () => @@ -387,7 +387,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(reply).toEqual({ outcome: { outcome: "cancelled" } }); expect(error.detail).toContain("permission or user input"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["file", "terminal", "extension"] as const)( @@ -416,7 +416,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { const error = yield* Fiber.join(child).pipe(Effect.flip); expect(error.detail).toContain("tool or user input"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -432,7 +432,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { .pipe(Effect.flip); expect(error.detail).toContain(detail); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("does not return partial JSON after native cancellation", () => @@ -449,7 +449,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { .pipe(Effect.flip); expect(error.detail).toContain("cancelled"); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -470,7 +470,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toBe(detail); expect(error.detail).not.toContain("Raw provider failure text."); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -517,7 +517,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toContain("wrote files"); if (target !== undefined) expect(yield* fs.exists(target)).toBe(true); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("uses the native default without sending T3's default selection as a model ID", () => @@ -530,7 +530,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(result).toEqual({ title: "Repair login" }); expect(fixture.state.selectedModels).toEqual([]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each([ @@ -562,7 +562,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(Exit.isSuccess(result)).toBe(available); expect(fixture.state.workspaces.length).toBe(available ? 1 : 0); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("does not launch during sign-out or before sign-in", () => @@ -575,7 +575,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(error.detail).toBe("Sign in before starting Antigravity."); expect(fixture.state.workspaces).toEqual([]); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect.each(["caller", "sign-out"] as const)( @@ -596,7 +596,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { } expect(fixture.state.cancellations).toBe(1); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); it.effect("refuses unsafe native session IDs without deleting other files", () => @@ -609,7 +609,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { expect(fixture.state.prompts).toEqual([]); expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.db`)).toBe("helper session"); expect(fixture.state.closed).toEqual(fixture.state.workspaces); - }).pipe(Effect.scoped), + }), ); it.effect("keeps native sessions whose metadata belongs to a different workspace", () => @@ -627,7 +627,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { "keep this session", ); expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.meta`)).toBe(metadata); - }).pipe(Effect.scoped), + }), ); }); @@ -640,5 +640,5 @@ it.effect("retains filesystem services supplied only during construction", () => title: "Repair login", }); yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + }), ); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index ae5c32bf57432..e6e43d606e27f 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -58,6 +58,7 @@ interface FakeCodexInput { mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number; requiredCwd?: string; requireInstructions?: string; + requireMcpServersOff?: ReadonlyArray; } function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { @@ -73,6 +74,7 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { mcpServers: input.mcpServers ?? [], requiredCwd: input.requiredCwd ?? null, requireInstructions: input.requireInstructions ?? null, + requireMcpServersOff: input.requireMcpServersOff ?? [], stderr: input.stderr ?? null, output: input.output, exitCode: input.exitCode ?? 0, @@ -129,6 +131,33 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { ' process.stderr.write(message + "\\n");', " process.exit(code);", "}", + "// Like Codex: a later mcp_servers={...} override replaces servers earlier -c flags defined.", + "const servers = new Map();", + "const offServers = new Set();", + "for (let index = 0; index < args.length; index += 1) {", + ' if (args[index] !== "-c" && args[index] !== "--config") continue;', + ' const value = args[index + 1] ?? "";', + ' if (value.startsWith("mcp_servers={")) {', + ' const named = [...value.matchAll(/"([^"]+)"=\\{enabled=false\\}/g)].map((match) => match[1]);', + " for (const name of named) offServers.add(name);", + " for (const name of [...servers.keys()]) {", + " if (named.includes(name)) servers.set(name, false);", + " else servers.delete(name);", + " }", + ' } else if (value.startsWith("mcp_servers.")) {', + ' const [name, key] = value.slice("mcp_servers.".length).split(/[.=]/);', + " if (value === `mcp_servers.${name}.enabled=false`) offServers.add(name);", + " // An enabled flag alone toggles a server another layer (config.toml) defines.", + ' if (key === "enabled" && !servers.has(name)) continue;', + ' servers.set(name, servers.get(name) === true || key === "url" || key === "command");', + " }", + "}", + "for (const [name, hasTransport] of servers) {", + ' if (!hasTransport) fail("Error loading config.toml: invalid transport in `mcp_servers." + name + "`", 12);', + "}", + "for (const name of check.requireMcpServersOff) {", + ' if (!offServers.has(name)) fail("MCP server left on: " + name, 13);', + "}", 'if (check.requiredCwd !== null && process.cwd() !== check.requiredCwd) fail("cannot inspect checkout", 10);', 'if (check.requireInstructions !== null && !instructions.includes(check.requireInstructions)) fail("missing writer task", 11);', "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {", @@ -365,7 +394,7 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { { name: "already-off", enabled: false }, ], requireArg: - '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}', + 'exec --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}} --config developer_instructions="Use', }, (textGeneration) => Effect.gen(function* () { @@ -384,6 +413,52 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("turns off an MCP server that launch args define without dropping its transport", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers.t3-code.url="http://127.0.0.1:1/mcp"' -c 'mcp_servers.t3-code.enabled=true'`, + mcpServers: [{ name: "t3-code", enabled: true }], + requireMcpServersOff: ["t3-code"], + requireArg: + "--config features.apps=false --config mcp_servers.t3-code.enabled=false --ephemeral", + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + + it.effect("keeps MCP servers off when launch args set their own mcp_servers table", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers={"my.server"={command="echo",enabled=true}}'`, + mcpServers: [ + { name: "my.server", enabled: true }, + { name: "my server", enabled: true }, + ], + requireArg: + '--config features.apps=false --config mcp_servers={"my.server"={enabled=false},"my server"={enabled=false}} --config mcp_servers.my server.enabled=false --ephemeral', + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + it.effect("still generates when Codex cannot list its MCP servers", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 4de5392502c8c..49c60166111ba 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -55,6 +55,11 @@ const codexMcpServersOff = (names: ReadonlyArray): string | null => names.length === 0 ? null : `mcp_servers={${names.map((name) => `${JSON.stringify(name)}={enabled=false}`).join(",")}}`; +// Codex splits -c keys at the first "=" and on every dot, so only those names take a dotted flag. +const codexMcpServerOffFlags = (names: ReadonlyArray) => + names + .filter((name) => !name.includes(".") && !name.includes("=")) + .flatMap((name) => ["--config", `mcp_servers.${name}.enabled=false`]); const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* ( codexConfig: CodexSettings, @@ -291,20 +296,28 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func } : {}), }; - const mcpServersOff = yield* listEnabledMcpServers({ + const enabledMcpServers = yield* listEnabledMcpServers({ binary, cwd, env, launchArgs: codexMcpListLaunchArgs(launchArgs), - }).pipe(Effect.map(codexMcpServersOff)); + }); + const mcpServersOff = codexMcpServersOff(enabledMcpServers); + const execLaunchArgs = codexExecLaunchArgs(launchArgs); + // A launch-arg mcp_servers={...} table replaces ours and can re-enable dotted names. + const launchArgsSetMcpTable = execLaunchArgs.some((arg) => /\bmcp_servers\s*=/.test(arg)); const spawnCommand = yield* resolveSpawnCommand( binary, [ "exec", - ...codexExecLaunchArgs(launchArgs), + // Before launch args: a later table would replace servers their -c flags define. + ...(mcpServersOff ? ["--config", mcpServersOff] : []), + ...execLaunchArgs, // A user's MCP server could act on the text-generation prompt. ...CODEX_NO_PLUGIN_ARGS, - ...(mcpServersOff ? ["--config", mcpServersOff] : []), + ...(mcpServersOff && launchArgsSetMcpTable ? ["--config", mcpServersOff] : []), + // After launch args, so a launch arg's enabled=true cannot turn a server back on. + ...codexMcpServerOffFlags(enabledMcpServers), "--ephemeral", "--skip-git-repo-check", "-s", diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts index 869cd1b4fb5e7..6cb1bfad71be7 100644 --- a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts @@ -70,7 +70,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { files: [{ uri: NodeURL.pathToFileURL(screenshotPath).href, name: "screen.png" }], }); } - }).pipe(Effect.scoped), + }), ); it.effect("keeps a provider's own error message out of the caller-visible detail", () => @@ -153,7 +153,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { .pipe(Effect.flip); assert.equal(failure.detail, "OpenCode could not generate the text."); assert.deepEqual(failure.cause, refusal); - }).pipe(Effect.scoped), + }), ); it.effect("times out when the prompt request and its interrupt never answer", () => @@ -219,6 +219,6 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { yield* TestClock.adjust("5 seconds"); const failure = yield* Fiber.join(generation); assert.equal(failure.detail, "OpenCode did not finish generating in time."); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index 274e63b46c906..d7e73a1da96c9 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -1,11 +1,21 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { expect, it } from "@effect/vitest"; -import { SecretProviderId, ServerConfigStreamEvent, UsageLimitSourceId } from "@t3tools/contracts"; +import { + ProviderDriverKind, + SecretProviderId, + ServerConfigStreamEvent, + UsageLimitSourceId, + type ServerProviderUsageWindow, + type UsageLimitSourceSnapshot, +} from "@t3tools/contracts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; @@ -26,6 +36,14 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => "hub.test:8317", "Usage limit source", ]); + // Only an http(s) hub URL names an endpoint an agent can be sent to. + expect(snapshots.map((source) => source.origin)).toEqual([ + undefined, + undefined, + undefined, + "https://hub.test:8317", + undefined, + ]); expect(() => encodeConfigEvent({ version: 1, @@ -87,7 +105,6 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => ), NodeCrypto.layer, ]), - Effect.scoped, ), ); @@ -154,6 +171,137 @@ it.effect("reads a management key from its secret provider", () => { ), NodeCrypto.layer, ]), - Effect.scoped, ); }); + +const NOW = Date.parse("2026-11-13T12:00:00.000Z"); +const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000)); +const spent = (id: string, hours: number): ServerProviderUsageWindow => ({ + id, + kind: "weekly", + label: id, + usedPercent: 100, + resetsAt: at(hours), +}); +const hub = ( + accounts: ReadonlyArray<{ + driver?: string; + windows?: ReadonlyArray; + unavailable?: true; + }>, +): UsageLimitSourceSnapshot => ({ + id: UsageLimitSourceId.make("hub"), + kind: "cliproxy", + label: "hub", + checkedAt: at(0), + accounts: accounts.map((account, index) => ({ + id: `account-${index}`, + driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"), + usageLimits: { + checkedAt: at(0), + windows: account.windows ?? [], + ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}), + }, + })), +}); + +it.each([ + { + name: "earliest refill when every account is spent, each at its latest spent window", + accounts: [ + { windows: [spent("five_hour", 1), spent("seven_day", 3)] }, + { windows: [spent("five_hour", 2)] }, + { driver: "codex", windows: [] }, + ], + model: "claude-haiku-5-5", + expected: at(2), + }, + { + name: "unknown while an account still has room", + accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown while an account could not be read", + accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown when a spent window has no reset or already reset", + accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks only its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-fable-5-2", + expected: at(5), + }, + { + name: "no account of the driver", + accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }], + model: "claude-haiku-5-5", + expected: null, + }, +])("hub pool reset: $name", ({ accounts, model, expected }) => { + expect( + UsageLimitSources.hubPoolResetAt( + [hub(accounts)], + ProviderDriverKind.make("claudeAgent"), + model, + NOW, + ), + ).toBe(expected); +}); + +it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" }; + const cached = { + ...roomLeft, + accounts: roomLeft.accounts.map((account) => ({ + ...account, + usageLimits: { + ...account.usageLimits, + windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })), + }, + })), + }; + let current: ReadonlyArray = [cached]; + let refresh: Effect.Effect = Effect.sync(() => { + current = [roomLeft]; + }); + const lookup = UsageLimitSources.UsageLimitResetFallback.pipe( + Effect.flatMap((fallback) => + fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null), + ), + Effect.provide( + UsageLimitSources.layerResetFallback.pipe( + Layer.provide( + Layer.mock(UsageLimitSources.UsageLimitSources)({ + current: Effect.sync(() => current), + refresh: Effect.suspend(() => refresh), + }), + ), + ), + ), + ); + // The last poll saw room; the account was spent after it. + expect(yield* lookup).toBe(at(2)); + current = [cached]; + refresh = Effect.never; + const stalled = yield* Effect.forkChild(lookup); + yield* TestClock.adjust("5 seconds"); + expect(yield* Fiber.join(stalled)).toBeNull(); + }), +); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 7d40b0fb9ecea..c591931843411 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -3,6 +3,7 @@ import { UsageLimitSourceError, type UsageLimitSourceConsumeResetCreditInput, type ProviderConsumeResetCreditResult, + type ProviderDriverKind, type ServerSettings, UsageLimitSourceConfig, settingsSecretLiteral, @@ -26,6 +27,7 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretReso import * as SecretResolverLayer from "../secrets/SecretResolver.ts"; import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts"; import * as Settings from "../serverSettings.ts"; +import { windowLimitsModel } from "../provider/claudeUsageLimits.ts"; import { makeCliproxyApi } from "./cliproxyApi.ts"; export class UsageLimitSources extends Context.Service< @@ -79,7 +81,14 @@ export const make = Effect.gen(function* () { config: UsageLimitSourceConfig, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); - const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const; + const url = URL.parse(config.url); + const base = { + id, + kind: config.kind, + label: sourceLabel(id, config), + ...(url && /^https?:$/.test(url.protocol) ? { origin: url.origin } : {}), + checkedAt, + } as const; const managementKey = yield* readManagementKey(config); if (managementKey.length === 0) { return { ...base, accounts: [], error: missingManagementKey(config) }; @@ -198,3 +207,64 @@ export const make = Effect.gen(function* () { export const layer = Layer.effect(UsageLimitSources, make).pipe( Layer.provide(SecretResolverLayer.layer), ); + +/** A hub answers with a usage limit only when every account it routes the driver to is spent. */ +export function hubPoolResetAt( + sources: ReadonlyArray, + driver: ProviderDriverKind, + model: string | null, + now: number, +): string | null { + let earliest: number | null = null; + for (const source of sources) { + for (const account of source.accounts) { + if (account.driver !== driver) continue; + // An unread account may be the one still blocked, so its refill is unknown. + if (account.usageLimits.unavailable) return null; + const spent = account.usageLimits.windows.filter( + (window) => window.usedPercent >= 100 && windowLimitsModel(window, model), + ); + if (spent.length === 0) return null; + const resets = spent.map((window) => Date.parse(window.resetsAt ?? "")); + if (resets.some((reset) => !Number.isFinite(reset))) return null; + const recoversAt = Math.max(...resets); + if (recoversAt <= now) return null; + earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt); + } + } + return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest)); +} + +export class UsageLimitResetFallback extends Context.Reference<{ + readonly resetAt: ( + driver: ProviderDriverKind, + endpoint: string, + model: string | null, + ) => Effect.Effect; +}>("t3/usage/UsageLimitResetFallback", { + defaultValue: () => ({ resetAt: () => Effect.succeed(null) }), +}) {} + +export const layerResetFallback = Layer.effect( + UsageLimitResetFallback, + Effect.gen(function* () { + const sources = yield* UsageLimitSources; + return { + resetAt: Effect.fn("UsageLimitResetFallback.resetAt")(function* (driver, endpoint, model) { + // Only the hub at the instance's endpoint serves its turns. + const atEndpoint = Effect.map(sources.current, (current) => + current.filter((source) => source.origin === endpoint), + ); + if ((yield* atEndpoint).length === 0) return null; + // The pool usually ran out after the last poll, so the cached accounts still show room. + yield* sources.refresh.pipe(Effect.timeout("5 seconds"), Effect.ignore); + return hubPoolResetAt( + yield* atEndpoint, + driver, + model, + DateTime.toEpochMillis(yield* DateTime.now), + ); + }), + }; + }), +); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index e1562070cf28f..81f3d1ec289aa 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -521,7 +521,7 @@ describe("Codex usage history", () => { }); describe("UsageService", () => { - it.live("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () => + it.effect("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () => Effect.gen(function* () { const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); @@ -631,10 +631,10 @@ describe("UsageService", () => { Effect.scoped, Effect.provide(layerService({ prefix: "usage-compressed-codex", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("keeps the first host identity across recreation and explicit override removal", () => + it.effect("keeps the first host identity across recreation and explicit override removal", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); @@ -662,10 +662,10 @@ describe("UsageService", () => { const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); assert.strictEqual(source?.fingerprint.hostId, expected); } - }).pipe(Effect.scoped), + }), ); - it.live("concurrent initialization keeps one host identity across service recreation", () => + it.effect("concurrent initialization keeps one host identity across service recreation", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); @@ -718,10 +718,10 @@ describe("UsageService", () => { const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); assert.strictEqual(source?.fingerprint.hostId, hostId); } - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers", () => Effect.gen(function* () { @@ -870,10 +870,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "keeps resolved Codex tiers when a grown pre-v15 cache entry re-parses without history", () => Effect.gen(function* () { @@ -966,10 +966,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "reads Pi per-model usage and auxiliary costs once across forks and repeated entries", () => Effect.gen(function* () { @@ -1155,10 +1155,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "reads Muse inference history once, persists appended usage, and reprices unknown models", () => Effect.gen(function* () { @@ -1377,10 +1377,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("returns other providers' usage while Muse home discovery is still pending", () => + it.effect("returns other providers' usage while Muse home discovery is still pending", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); @@ -1437,73 +1437,75 @@ describe("UsageService", () => { assert.deepStrictEqual(museSources(refreshed), [ [NodePath.join(museHome, "sessions"), "ok", undefined], ]); - }).pipe(Effect.scoped), + }), ); - it.live("reports missing Pi history and skips malformed records without losing valid usage", () => - Effect.gen(function* () { - const { home, settings } = yield* setup; - yield* Effect.gen(function* () { - const service = yield* UsageService.make; - const missing = yield* service.readSummary(WINDOW); - assert.strictEqual( - missing.sources.find((source) => source.fingerprint.provider === "pi")?.status, - "missing", - ); - const dir = NodePath.join(home, "pi", "sessions"); - yield* Effect.promise(async () => { - await NodeFSP.mkdir(dir, { recursive: true }); - await NodeFSP.writeFile( - NodePath.join(dir, "session.jsonl"), - [ - "{broken", - "null", - encodeUnknownJsonString({ type: "session", id: "valid" }), - encodeUnknownJsonString({ - type: "message", - id: "bad", - timestamp: "invalid", - message: { - role: "assistant", - provider: "openai", - model: "model", - usage: { input: 100 }, - }, - }), - encodeUnknownJsonString({ - type: "message", - id: "valid", - timestamp: "2026-08-01T10:00:00Z", - message: { - role: "assistant", - provider: "openai", - model: "model", - usage: { - input: -1, - cacheRead: "100", - output: 7, - reasoning: 50, - cost: { total: -1 }, - }, - }, - }), - ].join("\n") + "\n", + it.effect( + "reports missing Pi history and skips malformed records without losing valid usage", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const missing = yield* service.readSummary(WINDOW); + assert.strictEqual( + missing.sources.find((source) => source.fingerprint.provider === "pi")?.status, + "missing", ); - }); - const summary = yield* service.readSummary(WINDOW); - const pi = summary.buckets.filter((bucket) => bucket.provider === "pi"); - assert.strictEqual(pi.length, 1); - assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7); - assert.strictEqual(pi[0]?.totals.reasoningTokens, 7); - assert.strictEqual(pi[0]?.costSource, "unpriced"); - }).pipe( - Effect.scoped, - Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })), - ); - }).pipe(Effect.scoped), + const dir = NodePath.join(home, "pi", "sessions"); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(dir, "session.jsonl"), + [ + "{broken", + "null", + encodeUnknownJsonString({ type: "session", id: "valid" }), + encodeUnknownJsonString({ + type: "message", + id: "bad", + timestamp: "invalid", + message: { + role: "assistant", + provider: "openai", + model: "model", + usage: { input: 100 }, + }, + }), + encodeUnknownJsonString({ + type: "message", + id: "valid", + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + provider: "openai", + model: "model", + usage: { + input: -1, + cacheRead: "100", + output: 7, + reasoning: 50, + cost: { total: -1 }, + }, + }, + }), + ].join("\n") + "\n", + ); + }); + const summary = yield* service.readSummary(WINDOW); + const pi = summary.buckets.filter((bucket) => bucket.provider === "pi"); + assert.strictEqual(pi.length, 1); + assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7); + assert.strictEqual(pi[0]?.totals.reasoningTokens, 7); + assert.strictEqual(pi[0]?.costSource, "unpriced"); + }).pipe( + Effect.scoped, + Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })), + ); + }), ); - it.live("discovers Pi history in its default home and directory overrides", () => + it.effect("discovers Pi history in its default home and directory overrides", () => Effect.gen(function* () { const { home, settings } = yield* setup; for (const [agentDir, sessionDir, relativeDir, launchArgs, instanceHome, platform] of [ @@ -1607,10 +1609,10 @@ describe("UsageService", () => { Effect.provideService(HostProcess.HomeDirectory, home), ); } - }).pipe(Effect.scoped), + }), ); - it.live("reads shared managed default and disabled extra account history once", () => + it.effect("reads shared managed default and disabled extra account history once", () => Effect.gen(function* () { const { home, settings } = yield* setup; const summary = yield* Effect.gen(function* () { @@ -1687,10 +1689,10 @@ describe("UsageService", () => { ).length, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live("restores the Cursor account cache after a restart", () => + it.effect("restores the Cursor account cache after a restart", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1729,10 +1731,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () => + it.effect("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () => Effect.gen(function* () { const { settings, home } = yield* setup; const signIn = new TextEncoder().encode( @@ -1781,10 +1783,10 @@ describe("UsageService", () => { ]); assert.strictEqual(cursorSource(summary)?.status, "ok"); } - }).pipe(Effect.scoped), + }), ); - it.live("does not show a previous Cursor account's history after the API key changes", () => + it.effect("does not show a previous Cursor account's history after the API key changes", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1823,10 +1825,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("keeps a new Cursor key's refresh visible beside a failing key", () => + it.effect("keeps a new Cursor key's refresh visible beside a failing key", () => Effect.gen(function* () { const { settings, home } = yield* setup; const cursor = makeFakeCursor(); @@ -1908,10 +1910,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("reports one Cursor source when two API keys belong to the same account", () => + it.effect("reports one Cursor source when two API keys belong to the same account", () => Effect.gen(function* () { const { settings, home } = yield* setup; yield* TestClock.setTime(CURSOR_NOW); @@ -1970,10 +1972,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live( + it.effect( "includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account", () => Effect.gen(function* () { @@ -2027,10 +2029,10 @@ describe("UsageService", () => { ?.distinctSessions, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live("counts unpriced tokens from the unpriced records of a mixed model", () => + it.effect("counts unpriced tokens from the unpriced records of a mixed model", () => Effect.gen(function* () { const { settings, home } = yield* setup; const message = (id: string, cost: number, input: number, output: number, minute: number) => @@ -2064,10 +2066,10 @@ describe("UsageService", () => { assert.strictEqual(model?.costUsd, 1); assert.strictEqual(model?.totalTokens, 10_000); assert.strictEqual(model?.unpricedTokens, 9_900); - }).pipe(Effect.scoped), + }), ); - it.live("includes host and merged OpenCode instance histories once across list aliases", () => + it.effect("includes host and merged OpenCode instance histories once across list aliases", () => Effect.gen(function* () { const { settings, home } = yield* setup; const hostRoot = NodePath.join(home, "opencode"); @@ -2143,10 +2145,10 @@ describe("UsageService", () => { .sort((a, b) => a - b), [5, 7, 11], ); - }).pipe(Effect.scoped), + }), ); - it.live("counts aliased OpenCode and Antigravity directories once", () => + it.effect("counts aliased OpenCode and Antigravity directories once", () => Effect.gen(function* () { const { settings, home } = yield* setup; const opencode = NodePath.join(home, "opencode-store"); @@ -2197,10 +2199,10 @@ describe("UsageService", () => { sourcesFor("antigravity")[0]?.fingerprint.resolvedHomePath, yield* Effect.promise(() => NodeFSP.realpath(conversations)), ); - }).pipe(Effect.scoped), + }), ); - it.live("reads Antigravity history from each instance's data directory", () => + it.effect("reads Antigravity history from each instance's data directory", () => Effect.gen(function* () { const { settings, home } = yield* setup; const first = NodePath.join(home, "antigravity-first"); @@ -2268,10 +2270,10 @@ describe("UsageService", () => { outputTokens, ); } - }).pipe(Effect.scoped), + }), ); - it.live("reads configured and disabled accounts once across shared and aliased homes", () => + it.effect("reads configured and disabled accounts once across shared and aliased homes", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const codexHome = NodePath.join(home, "codex-account"); @@ -2337,6 +2339,7 @@ describe("UsageService", () => { }, [ProviderInstanceId.make("codex-work")]: { driver: ProviderDriverKind.make("codex"), + config: { shadowHomePath: NodePath.join(home, "work-shadow") }, environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }], }, [ProviderInstanceId.make("codex-alias")]: { @@ -2386,10 +2389,10 @@ describe("UsageService", () => { sources.filter((source) => source.fingerprint.provider === "codex").length, 1, ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "uses explicit account settings before environment and default homes, then refreshes them", () => Effect.gen(function* () { @@ -2469,10 +2472,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "uses inherited home variables when explicit default accounts have no home settings", () => Effect.gen(function* () { @@ -2515,10 +2518,10 @@ describe("UsageService", () => { .resolvedHomePath, NodePath.join(home, "grok", "sessions"), ); - }).pipe(Effect.scoped), + }), ); - it.live.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( "reports unreadable transcripts as partial and recovers once they can be read", () => Effect.gen(function* () { @@ -2543,10 +2546,10 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-unreadable", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "answers a provisional read from the last scan, then the exact read adds what changed", () => Effect.gen(function* () { @@ -2612,10 +2615,10 @@ describe("UsageService", () => { Effect.scoped, Effect.provide(layerService({ prefix: "usage-service-provisional", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("filters original model IDs before aliases, pricing, buckets and session counts", () => + it.effect("filters original model IDs before aliases, pricing, buckets and session counts", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => @@ -2717,10 +2720,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("reprices unchanged transcripts when custom prices are added, edited, or removed", () => + it.effect("reprices unchanged transcripts when custom prices are added, edited, or removed", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model"))); @@ -2761,10 +2764,10 @@ describe("UsageService", () => { layerService({ prefix: "usage-service-price-overrides-test", home, settings }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "retains Codex reconciliation and partial coverage through persisted restart, append and repair", () => Effect.gen(function* () { @@ -2884,10 +2887,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "merges partial Claude copies through tail replacement, newline completion and restart", () => Effect.gen(function* () { @@ -2943,10 +2946,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live( + it.effect( "keeps large-record totals and costs exact through append, dedupe, restart and cleanup", () => Effect.gen(function* () { @@ -2998,13 +3001,14 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])( + it.effect.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])( "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts, removes the old file", (version) => Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z")); const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); const rollout = (sessionId: string, outputTokens: number) => @@ -3128,10 +3132,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("re-parses a clean v10 Codex rollout that grew after an interrupted request", () => + it.effect("re-parses a clean v10 Codex rollout that grew after an interrupted request", () => Effect.gen(function* () { const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); @@ -3228,10 +3232,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => + it.effect("preserves saved tokens, costs and sessions after transcript cleanup and restart", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const alias = NodePath.join(home, "claude-alias"); @@ -3329,10 +3333,10 @@ describe("UsageService", () => { }), ), ); - }).pipe(Effect.scoped), + }), ); - it.live("credits the same copy of a duplicate after its transcripts are deleted", () => + it.effect("credits the same copy of a duplicate after its transcripts are deleted", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; const dir = NodePath.dirname(transcript); @@ -3367,10 +3371,10 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-copy-order-test", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("credits the same copy of a duplicate from the last scan as an exact read does", () => + it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); const { transcript, settings, home } = yield* setup; @@ -3425,10 +3429,10 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-narrow-order-test", home, settings })), ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "keeps a newer cached read when a slower scan of another window finishes later", () => Effect.gen(function* () { @@ -3455,53 +3459,56 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-stale-read-test", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live("keeps an absent directory missing when its cached files only contain diagnostics", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => - NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }), - ); - yield* Effect.gen(function* () { - const { stateDir } = yield* ServerConfig.ServerConfig; - const mtimeMs = yield* Clock.currentTimeMillis; - const cache = makeScanCacheWriter()( - new Map([ - [ - transcript, - { - size: 0, - mtimeMs, - provider: "claude" as const, - records: [], - tailRecords: [], - malformedRecords: 2, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }, - ], - ]), - {}, + it.effect( + "keeps an absent directory missing when its cached files only contain diagnostics", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z")); + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => + NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }), ); - yield* Effect.promise(async () => { - await NodeFSP.mkdir(stateDir, { recursive: true }); - await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache); - }); - const summary = yield* (yield* UsageService.make).readSummary(WINDOW); - const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); - assert.strictEqual(source?.status, "missing"); - assert.strictEqual(source?.scannedFiles, 0); - assert.strictEqual(source?.malformedRecords, 2); - }).pipe( - Effect.provide( - layerService({ prefix: "usage-service-missing-diagnostics", home, settings }), - ), - ); - }).pipe(Effect.scoped), + yield* Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const mtimeMs = yield* Clock.currentTimeMillis; + const cache = makeScanCacheWriter()( + new Map([ + [ + transcript, + { + size: 0, + mtimeMs, + provider: "claude" as const, + records: [], + tailRecords: [], + malformedRecords: 2, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ], + ]), + {}, + ); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(stateDir, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache); + }); + const summary = yield* (yield* UsageService.make).readSummary(WINDOW); + const source = summary.sources.find((source) => source.fingerprint.provider === "claude"); + assert.strictEqual(source?.status, "missing"); + assert.strictEqual(source?.scannedFiles, 0); + assert.strictEqual(source?.malformedRecords, 2); + }).pipe( + Effect.provide( + layerService({ prefix: "usage-service-missing-diagnostics", home, settings }), + ), + ); + }), ); - it.live("reports saved usage of a removed directory only for windows it reaches", () => + it.effect("reports saved usage of a removed directory only for windows it reaches", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-12T00:00:00Z")); const { transcript, settings, home } = yield* setup; @@ -3532,10 +3539,10 @@ describe("UsageService", () => { assert.deepStrictEqual(later.buckets, []); assert.strictEqual(later.sources[0]?.status, "missing"); assert.strictEqual(later.sources[0]?.scannedFiles, 0); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + }), ); - it.live("does not share an in-flight scan after custom prices change", () => + it.effect("does not share an in-flight scan after custom prices change", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model"))); @@ -3601,10 +3608,10 @@ describe("UsageService", () => { }).pipe( Effect.provide(layerService({ prefix: "usage-service-price-race-test", home, settings })), ); - }).pipe(Effect.scoped), + }), ); - it.live.each(["network", "http", "invalidJson", "empty"] as const)( + it.effect.each(["network", "http", "invalidJson", "empty"] as const)( "recovers pricing through the GitHub API after a %s failure", (failure) => Effect.gen(function* () { @@ -3660,10 +3667,10 @@ describe("UsageService", () => { assert.strictEqual(cached.pricing.status, "cached"); assert.deepStrictEqual(cached.buckets, summary.buckets); assert.strictEqual(requests.length, 2); - }).pipe(Effect.scoped), + }), ); - it.live("does not orphan an in-flight scan when its first caller is interrupted", () => + it.effect("does not orphan an in-flight scan when its first caller is interrupted", () => Effect.gen(function* () { const { settings, home } = yield* setup; const service = yield* UsageService.make.pipe( @@ -3738,6 +3745,6 @@ describe("UsageService", () => { orphanedAt, `interruption left the next matching request pending at scheduler check ${orphanedAt}`, ); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index d80c51964a20c..a4b10a4df2045 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -43,6 +43,7 @@ export interface TranscriptParseResult { export const GUARD_LENGTH = 64; const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024; +const READ_CHUNK_BYTES = 256 * 1024; const NEWLINE = 0x0a; const STAT_CONCURRENCY = 32; const WALK_CONCURRENCY = 16; @@ -168,6 +169,29 @@ async function guardMatches( } } +/** Plain files reuse one buffer, so a chunk is only valid until the next one is requested. */ +async function* readChunks( + handle: NodeFSP.FileHandle, + start: number, + compressed: boolean, +): AsyncGenerator { + if (compressed) { + // Compressed snapshots cache a full parse; decoded byte offsets cannot + // resume the compressed input. + yield* handle + .createReadStream({ start, autoClose: true, highWaterMark: READ_CHUNK_BYTES }) + .compose(NodeZlib.createZstdDecompress()); + return; + } + const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES); + for (let position = start; ;) { + const { bytesRead } = await handle.read(buffer, 0, buffer.length, position); + if (bytesRead === 0) return; + position += bytesRead; + yield buffer.subarray(0, bytesRead); + } +} + // Match markers in one latin1 alternation; one character per byte preserves exact ASCII offsets. export function transcriptLineGate(markers: readonly [string, ...string[]]) { if (markers.length === 1) { @@ -244,7 +268,8 @@ export async function readTranscriptRecords( const append = (segment: Buffer) => { if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) { - if (segment.length > 0) pendingChunks.push(segment); + // Copy: the next read overwrites the chunk this segment points into. + if (segment.length > 0) pendingChunks.push(Buffer.from(segment)); pendingBytes += segment.length; return; } @@ -275,15 +300,7 @@ export async function readTranscriptRecords( streaming = undefined; decoder = undefined; }; - const input = handle.createReadStream({ - start, - autoClose: compressed, - highWaterMark: 256 * 1024, - }); - // Compressed snapshots cache a full parse; decoded byte offsets cannot - // resume the compressed input. - const stream = compressed ? input.compose(NodeZlib.createZstdDecompress()) : input; - for await (const chunk of stream) { + for await (const chunk of readChunks(handle, start, compressed)) { let lineStart = 0; while (lineStart < chunk.length) { const newlineIndex = chunk.indexOf(NEWLINE, lineStart); diff --git a/apps/server/src/utils/subscribeBeforeSnapshot.test.ts b/apps/server/src/utils/subscribeBeforeSnapshot.test.ts index 70f0beda25ce6..e37b969a123dc 100644 --- a/apps/server/src/utils/subscribeBeforeSnapshot.test.ts +++ b/apps/server/src/utils/subscribeBeforeSnapshot.test.ts @@ -15,70 +15,66 @@ import { describe("subscribeBeforeSnapshot", () => { it.effect("atomically reads the initial snapshot before receiving later changes", () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* PubSub.sliding(1); - const latest = yield* Ref.make(1); - const mutex = yield* Semaphore.make(1); - const snapshotStarted = yield* Deferred.make(); - const finishSnapshot = yield* Deferred.make(); - const subscriptionFiber = yield* subscribeBeforeSnapshot( - changes, - Deferred.succeed(snapshotStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSnapshot)), - Effect.andThen(Ref.get(latest)), - ), - mutex, - ).pipe(Effect.forkChild); + Effect.gen(function* () { + const changes = yield* PubSub.sliding(1); + const latest = yield* Ref.make(1); + const mutex = yield* Semaphore.make(1); + const snapshotStarted = yield* Deferred.make(); + const finishSnapshot = yield* Deferred.make(); + const subscriptionFiber = yield* subscribeBeforeSnapshot( + changes, + Deferred.succeed(snapshotStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSnapshot)), + Effect.andThen(Ref.get(latest)), + ), + mutex, + ).pipe(Effect.forkChild); - yield* Deferred.await(snapshotStarted); - const publishFiber = yield* mutex - .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2)))) - .pipe(Effect.forkChild); - yield* Deferred.succeed(finishSnapshot, undefined); + yield* Deferred.await(snapshotStarted); + const publishFiber = yield* mutex + .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2)))) + .pipe(Effect.forkChild); + yield* Deferred.succeed(finishSnapshot, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); - yield* Fiber.join(publishFiber); - const firstChange = yield* subscription.changes.pipe( - Stream.runHead, - Effect.timeout("1 second"), - ); + const subscription = yield* Fiber.join(subscriptionFiber); + yield* Fiber.join(publishFiber); + const firstChange = yield* subscription.changes.pipe( + Stream.runHead, + Effect.timeout("1 second"), + ); - expect(subscription.latest).toBe(1); - expect(firstChange).toEqual(Option.some(2)); - }), - ), + expect(subscription.latest).toBe(1); + expect(firstChange).toEqual(Option.some(2)); + }), ); it.effect("subscribes before an uncoordinated snapshot can change", () => - Effect.scoped( - Effect.gen(function* () { - const changes = yield* PubSub.sliding(1); - const latest = yield* Ref.make(1); - const snapshotStarted = yield* Deferred.make(); - const finishSnapshot = yield* Deferred.make(); - const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex( - changes, - Deferred.succeed(snapshotStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishSnapshot)), - Effect.andThen(Ref.get(latest)), - ), - ).pipe(Effect.forkChild); + Effect.gen(function* () { + const changes = yield* PubSub.sliding(1); + const latest = yield* Ref.make(1); + const snapshotStarted = yield* Deferred.make(); + const finishSnapshot = yield* Deferred.make(); + const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex( + changes, + Deferred.succeed(snapshotStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSnapshot)), + Effect.andThen(Ref.get(latest)), + ), + ).pipe(Effect.forkChild); - yield* Deferred.await(snapshotStarted); - yield* Ref.set(latest, 2); - yield* PubSub.publish(changes, 2); - yield* Deferred.succeed(finishSnapshot, undefined); + yield* Deferred.await(snapshotStarted); + yield* Ref.set(latest, 2); + yield* PubSub.publish(changes, 2); + yield* Deferred.succeed(finishSnapshot, undefined); - const subscription = yield* Fiber.join(subscriptionFiber); - const firstChange = yield* subscription.changes.pipe( - Stream.runHead, - Effect.timeout("1 second"), - ); + const subscription = yield* Fiber.join(subscriptionFiber); + const firstChange = yield* subscription.changes.pipe( + Stream.runHead, + Effect.timeout("1 second"), + ); - expect(subscription.latest).toBe(2); - expect(firstChange).toEqual(Option.some(2)); - }), - ), + expect(subscription.latest).toBe(2); + expect(firstChange).toEqual(Option.some(2)); + }), ); }); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 89580e0937af7..61ad4729872eb 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1273,6 +1273,87 @@ it.effect("restores a checkpoint before the first commit without staging its fil }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("restores edits to skip-worktree files whose checkpoint content matches HEAD", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-skip-worktree-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const skippedPath = path.join(cwd, "skipped.txt"); + yield* fileSystem.writeFileString(skippedPath, "original\n"); + yield* git(["add", "skipped.txt"]); + yield* git(["commit", "-m", "add skipped file"]); + yield* git(["update-index", "--skip-worktree", "skipped.txt"]); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + yield* fileSystem.writeFileString(skippedPath, "later\n"); + + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }), + ); + + assert.strictEqual(yield* fileSystem.readFileString(skippedPath), "original\n"); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("sparse restore rewrites manual skip-worktree files and keeps exclusions absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + // One byte per chunk, so the index listing splits inside every record. + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + const onStdoutChunk = input.onStdoutChunk; + return liveProcess.run( + onStdoutChunk === undefined + ? input + : { + ...input, + onStdoutChunk: (chunk) => { + for (let index = 0; index < chunk.length; index++) + onStdoutChunk(chunk.subarray(index, index + 1)); + }, + }, + ); + }, + }), + ); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sparse-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + for (const name of ["in/normal", "in/skipped", "in/s space", "out/deep/absent", "out/stray"]) { + yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true }); + yield* fs.writeFileString(path.join(cwd, name), "original\n"); + } + yield* git(["add", "."]); + yield* git(["commit", "-m", "sparse fixture"]); + yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "in"]); + // Keeps Git from clearing the bit on files that are present. + yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]); + yield* git(["update-index", "--skip-worktree", "in/skipped", "in/s space"]); + const captureCwd = path.join(cwd, "in"); + yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef }); + yield* fs.writeFileString(path.join(cwd, "in/skipped"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/s space"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/normal"), "later\n"); + + for (const restoreCwd of [captureCwd, cwd]) { + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ + cwd: restoreCwd, + checkpointRef, + fallbackToHead: false, + }), + ); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/skipped")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/s space")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/normal")), "original\n"); + assert.isFalse(yield* fs.exists(path.join(cwd, "out"))); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + // The real VCS process, spawning `command` wherever the driver runs git. const vcsProcessSpawning = (command: string) => Layer.effect( diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ff0eac7c00093..813ea0f8abef4 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1390,20 +1390,90 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); // An empty index and checkpoint have nothing for git restore's pathspec to match. if (tracked.stdout.length > 0) { + const sparseConfig = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--bool", "core.sparseCheckout"], + allowNonZeroExit: true, + }); + const sparseCheckout = sparseConfig.stdout.trim() === "true"; + const restore = [...longPaths, "restore", "--source", commitOid, "--worktree", "--staged"]; + // restore leaves skip-worktree paths alone. Outside a sparse checkout every such bit was + // set by hand and capture recorded the file, so override them all. yield* execute({ operation, cwd: input.cwd, - args: [ - ...longPaths, - "restore", - "--source", - commitOid, - "--worktree", - "--staged", - "--", - ".", - ], + args: [...restore, ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), "--", "."], }); + if (sparseCheckout) { + // Sparse exclusions stay excluded; only skip-worktree paths the rules select are manual. + const manual = yield* Effect.gen(function* () { + const skipped: string[] = []; + let recordStart = true; + let keep = false; + let record: Uint8Array[] = []; + yield* vcsProcess.run({ + operation, + command: "git", + cwd: input.cwd, + args: ["ls-files", "--full-name", "--sparse", "-v", "-z", "--", "."], + maxOutputBytes: 4_096, + outputMode: "truncate", + // The index can be huge; keep only the "S "/"s " records of the NUL-delimited list. + onStdoutChunk: (chunk) => { + let start = 0; + while (start < chunk.length) { + const end = chunk.indexOf(0, start); + if (recordStart) { + keep = chunk[start] === 83 || chunk[start] === 115; + record = []; + } + if (keep) { + record.push(Buffer.from(chunk.subarray(start, end === -1 ? undefined : end))); + if (end !== -1) { + const entry = Buffer.concat(record).subarray(2); + record = []; + // Sparse directory entries are exclusions; stdin cannot carry non-UTF-8. + if (entry.at(-1) !== 47 && NodeBuffer.isUtf8(entry)) + skipped.push(entry.toString("utf8")); + } + } + recordStart = end !== -1; + if (!recordStart) break; + start = end + 1; + } + }, + }); + if (skipped.length === 0) return skipped; + const stdin = skipped.join("\0") + "\0"; + // check-rules echoes a subset of its input, so the input size bounds its output. + const rules = yield* execute({ + operation, + cwd: input.cwd, + args: ["sparse-checkout", "check-rules", "-z"], + stdin, + maxOutputBytes: Buffer.byteLength(stdin), + outputMode: "error", + }); + return rules.stdout.split("\0").filter((entry) => entry.length > 0); + }).pipe( + // A Git without ls-files --sparse or check-rules keeps the plain restore's result. + Effect.orElseSucceed((): string[] => []), + ); + if (manual.length > 0) { + yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...restore, + "--ignore-skip-worktree-bits", + "--pathspec-from-file=-", + "--pathspec-file-nul", + ], + stdin: manual.map((entry) => `:(top,literal)${entry}\0`).join(""), + }); + } + } } // Restoring away the last tracked file can remove a nested workspace directory. const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe( diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index cf00e46cb923c..55f05a0cecb3c 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2189,6 +2189,55 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("explains a non-fast-forward push from a host with a translated Git", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + const other = yield* makeTmpDir("git-other-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "--set-upstream", "origin", initialBranch]); + yield* git(other, ["clone", "--branch", initialBranch, remote, "."]); + yield* git(other, [ + "-c", + "user.email=t@t", + "-c", + "user.name=T", + "commit", + "--allow-empty", + "-m", + "remote", + ]); + yield* git(other, ["push", "origin", initialBranch]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "local"]); + const locales: Array = []; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("push")) { + locales.push(command.options.env?.LANGUAGE); + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const hostEnv = yield* HostProcess.Environment; + + const error = yield* driver + .pushCurrentBranch(cwd, null) + .pipe( + Effect.provideService(HostProcess.Environment, { ...hostEnv, LANGUAGE: "de" }), + Effect.flip, + ); + + assert.equal(error.reason, "push_rejected_non_fast_forward"); + assert.isNotEmpty(locales); + for (const locale of locales) assert.equal(locale, "C"); + }), + ); + it.effect("lets a slow remote branch checkout finish without blocking config writes", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4274,6 +4323,39 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { insertions: 1, deletions: 1, }); + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + assert.deepStrictEqual( + preview.sources.find((source) => source.kind === "working-tree")?.files, + [ + { path: "asset.data", previousPath: null, additions: 0, deletions: 1 }, + { path: "ordinary.txt", previousPath: null, additions: 1, deletions: 0 }, + ], + ); + }), + ); + + it.effect("keeps an oversized untracked file out of the review diff", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* writeTextFile(cwd, "README.md", "# tracked change\n"); + yield* writeTextFile(cwd, "ordinary.txt", "new\n"); + yield* writeTextFile(cwd, "large.data", ""); + // Sparse: the logical size is over the budget without allocating it. + yield* fileSystem.truncate(pathService.join(cwd, "large.data"), 257 * 1024 * 1024); + + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + + const source = preview.sources.find((source) => source.kind === "working-tree")!; + assert.isUndefined(source.files); + assert.isUndefined(source.patchesDeferred); + assert.isTrue(source.truncated); + assert.include(source.diff, "+# tracked change"); + assert.include(source.diff, "b/ordinary.txt"); + assert.notInclude(source.diff, "large.data"); }), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 56908ea754056..50bc37c6e79ec 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -81,8 +81,8 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; -// git diff --numstat reads every untracked byte (~5 ms/MB), so status totals skip larger untracked input. -const UNTRACKED_TOTALS_MAX_BYTES = 256 * 1024 * 1024; +// git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index. +const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024; // The listing walks the whole untracked tree before the cap applies, so a folder whose listing // failed (too many files, output limit, timeout) is not listed again on every status poll. const UNTRACKED_TOTALS_RETRY_MIN_MS = 60_000; @@ -2912,7 +2912,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { const publishBranch = yield* resolvePublishBranchName(cwd, branch); - yield* runGit( + yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, ["push", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`], @@ -3006,7 +3006,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } } - yield* runGit( + yield* executeGitWithStableDiagnostics( upstream ? "GitVcsDriver.pushCurrentBranch.pushOwnBranch" : "GitVcsDriver.pushCurrentBranch.pushWithUpstream", @@ -3023,7 +3023,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } if (destination?.upstream) { - yield* runGit( + yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, ["push", "--", destination.remoteName, `HEAD:refs/heads/${destination.branchName}`], @@ -3037,7 +3037,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } - yield* runGit("GitVcsDriver.pushCurrentBranch.push", cwd, ["push"], { timeoutMs: null }); + yield* executeGitWithStableDiagnostics("GitVcsDriver.pushCurrentBranch.push", cwd, ["push"], { + timeoutMs: null, + }); return { status: "pushed" as const, branch, @@ -3240,7 +3242,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const prepareReviewIndex = Effect.fn("prepareReviewIndex")(function* ( cwd: string, untrackedPaths: ReadonlyArray, - maxBytes?: number, + allowPartial: boolean, ) { const [stagedDeletionsStdout, indexValue] = yield* Effect.all( [ @@ -3268,21 +3270,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { concurrency: 2 }, ); const stagedDeletions = new Set(stagedDeletionsStdout.split("\0").filter(Boolean)); - const pathsToAdd = untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)); - if (pathsToAdd.length === 0) return undefined; - if (maxBytes !== undefined) { - const sizes = yield* Effect.forEach( - pathsToAdd, - (relativePath) => - fileSystem.lstat(path.resolve(cwd, relativePath)).pipe( - Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)), - Effect.orElseSucceed(() => 0), - ), - { concurrency: 16 }, - ); - // null: over the byte budget, so the caller reports totals as unavailable. - if (sizes.reduce((total, size) => total + size, 0) > maxBytes) return null; + // Staged deletions never enter the index, so their worktree copies must not spend the budget. + const candidates = untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)); + const sizes = yield* Effect.forEach( + candidates, + (relativePath) => + fileSystem.lstat(path.resolve(cwd, relativePath)).pipe( + Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)), + Effect.orElseSucceed(() => 0), + Effect.map((size) => ({ relativePath, size })), + ), + { concurrency: 16 }, + ); + // Smallest first, so which files fit does not depend on how their names sort. + const pathsToAdd: string[] = []; + let bytes = 0; + for (const { relativePath, size } of sizes.toSorted((left, right) => left.size - right.size)) { + bytes += size; + if (bytes > REVIEW_UNTRACKED_MAX_BYTES) break; + pathsToAdd.push(relativePath); } + const omitted = pathsToAdd.length < candidates.length; + if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted }; const indexPath = path.isAbsolute(indexValue.trim()) ? indexValue.trim() @@ -3335,7 +3344,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { env, stdin: `${pathsToAdd.join("\0")}\0` }, ); - return env; + return { env, omitted }; }); const readEmptyTreeHash = Effect.fn("readEmptyTreeHash")(function* (cwd: string) { @@ -3351,8 +3360,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const prepareUntrackedReviewIndexOrReason = Effect.fn("prepareUntrackedReviewIndex")(function* ( cwd: string, pathArgs: ReadonlyArray, - onlyPath?: string, - maxBytes?: number, + onlyPath: string | undefined, + allowPartial: boolean, ) { const untracked = yield* executeGit( "GitVcsDriver.review.listUntracked", @@ -3371,10 +3380,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (candidate) => onlyPath === undefined || candidate === onlyPath || candidate === `${onlyPath}/`, ); - if (paths.length === 0) return { env: undefined }; + if (paths.length === 0) return { env: undefined, omitted: false }; if (paths.length > REVIEW_UNTRACKED_MAX_FILES) return { unavailable: "Too many untracked files to count." }; - const env = yield* prepareReviewIndex(cwd, paths, maxBytes).pipe( + const index = yield* prepareReviewIndex(cwd, paths, allowPartial).pipe( Effect.catchTags({ PlatformError: (cause) => Effect.fail( @@ -3388,15 +3397,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }), ); - if (env === null) return { unavailable: "Untracked files are too large to count." }; - return { env }; + if (index.omitted && !allowPartial) + return { unavailable: "Untracked files are too large to count." }; + return index; }); const prepareUntrackedReviewIndex = ( cwd: string, pathArgs: ReadonlyArray, onlyPath?: string, ) => - prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath).pipe( + prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath, true).pipe( Effect.map((result) => ("unavailable" in result ? null : result)), ); @@ -3488,12 +3498,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } // Empty status can mean untracked files are hidden; retain the full scan. - const untracked = yield* prepareUntrackedReviewIndexOrReason( - cwd, - pathspecs, - undefined, - UNTRACKED_TOTALS_MAX_BYTES, - ); + const untracked = yield* prepareUntrackedReviewIndexOrReason(cwd, pathspecs, undefined, false); if ("unavailable" in untracked) { const count = remembered?.roots === rootsKey ? remembered.count + 1 : 1; untrackedTotalsFailures.delete(cwd); @@ -3844,9 +3849,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { const untracked = input.trackedOnly - ? { env: undefined } + ? { env: undefined, omitted: false } : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); - const metadataOnly = input.metadataOnly === true && !input.file && untracked !== null; + // Untracked files left out make the file list partial, so the bounded patch is sent instead. + const complete = untracked !== null && !untracked.omitted; + const metadataOnly = input.metadataOnly === true && !input.file && complete; const [dirty, base] = review.mergeBase === dirtyRef ? yield* readTrackedDiff(dirtyRef, untracked?.env, metadataOnly).pipe( @@ -3859,7 +3866,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { concurrency: 2 }, ); - if (untracked !== null) return [dirty, base] as const; + if (complete) return [dirty, base] as const; const incomplete = (ref: string | null, result: typeof dirty) => ref === null ? result : { ...result, files: undefined, stdoutTruncated: true }; return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts index b87dbf5e78250..18eaebe6e0959 100644 --- a/apps/server/src/vcs/VcsProcess.test.ts +++ b/apps/server/src/vcs/VcsProcess.test.ts @@ -92,7 +92,7 @@ describe("VcsProcess.run", () => { yield* fs.remove(lock); yield* git(restore); expect(yield* fs.readFileString(file)).toBe("before\n"); - }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(provideLive, Effect.provide(NodeServices.layer)), ); it.effect.each([ diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 87620e5d4fc4f..73093af6c750b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -71,6 +71,7 @@ const remoteStatusWithPr: VcsStatusRemoteResult = { function layerTestFor(state: { currentLocalStatus: VcsStatusLocalResult; currentRemoteStatus: VcsStatusRemoteResult | null; + currentDivergence?: Pick; localStatusCalls: number; remoteStatusCalls: number; localInvalidationCalls: number; @@ -133,6 +134,16 @@ function layerTestFor(state: { : (state.beforeCurrentBranch ?? Effect.void).pipe( Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), + upstreamDivergence: () => + Effect.sync(() => + state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null + ? { + refName: state.currentLocalStatus.refName, + aheadCount: (state.currentDivergence ?? state.currentRemoteStatus).aheadCount, + behindCount: (state.currentDivergence ?? state.currentRemoteStatus).behindCount, + } + : null, + ), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -239,7 +250,7 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.refreshLocalStatus("/repo"); assert.strictEqual(state.localStatusCalls, 3); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect( @@ -334,7 +345,7 @@ describe("VcsStatusBroadcaster", () => { ]); assert.deepEqual(yield* branches, [{ refName: null, isRepo: false }]); assert.equal(state.remoteStatusCalls, 0); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }, ); @@ -371,7 +382,7 @@ describe("VcsStatusBroadcaster", () => { yield* Fiber.join(detailsFiber), Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), ); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes terminal branch switches and validates cached status reads", () => { @@ -528,6 +539,48 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect.each([0, 2])( + "refreshes merge divergence while a lookup ends with %s commits behind", + (behindAfterLookup) => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: { ...baseRemoteStatus, aheadCount: 2, behindCount: 3 }, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + backgroundWorkEnabled: false, + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + ); + const lookup = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(started); + state.currentRemoteStatus = { ...baseRemoteStatus, aheadCount: 4, behindCount: 0 }; + yield* broadcaster.refreshLocalStatus("/repo"); + const status = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.equal(status.aheadCount, 4); + assert.equal(status.behindCount, 0); + assert.equal(state.remoteStatusCalls, 1); + state.currentDivergence = { aheadCount: 4, behindCount: behindAfterLookup }; + state.currentRemoteStatus = + behindAfterLookup > 0 + ? { ...baseRemoteStatus, ...state.currentDivergence } + : { ...baseRemoteStatus, aheadCount: 2, behindCount: 3 }; + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(lookup); + const afterLookup = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.equal(afterLookup.aheadCount, 4); + assert.equal(afterLookup.behindCount, behindAfterLookup); + }).pipe(Effect.provide(layerTestFor(state))); + }, + ); + it.effect("a local-only refresh after a branch switch leaves the PR refresh able to read", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -747,7 +800,7 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual(refreshed, remoteStatusWithPr); const final = yield* broadcaster.getStatus({ cwd: "/repo" }); assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr); - }).pipe(Effect.provide(layer), Effect.scoped); + }).pipe(Effect.provide(layer)); }); it.effect("an initial status read cannot overwrite an explicit refresh", () => { @@ -791,7 +844,7 @@ describe("VcsStatusBroadcaster", () => { (yield* broadcaster.getStatus({ cwd: "/repo" })).pr, remoteStatusWithPr.pr, ); - }).pipe(Effect.provide(layer), Effect.scoped); + }).pipe(Effect.provide(layer)); }); it.effect("keeps the published local snapshot when a refresh remote read fails", () => { @@ -977,7 +1030,7 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(polled); const status = yield* broadcaster.getStatus({ cwd: "/repo" }); assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("an explicit refresh reads local totals after the fetch", () => { @@ -1077,7 +1130,7 @@ describe("VcsStatusBroadcaster", () => { const status = yield* Fiber.join(refresh); assert.isTrue(status.hasWorkingTreeChanges); assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes local changes before a remote error and propagates that error", () => { @@ -1139,7 +1192,7 @@ describe("VcsStatusBroadcaster", () => { assert.isTrue(cached.hasWorkingTreeChanges); assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr); assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)( @@ -1225,7 +1278,7 @@ describe("VcsStatusBroadcaster", () => { assert.isNull(status.pr); assert.equal(status.aheadCount, 0); assert.equal(status.behindCount, 0); - }).pipe(Effect.provide(layerTest), Effect.scoped); + }).pipe(Effect.provide(layerTest)); }, ); @@ -1275,7 +1328,7 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr); assert.equal(cached.aheadCount, 2); assert.equal(state.remoteStatusCalls, 2); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("a terminal checkout publishes the new branch without waiting for a poll", () => @@ -1307,7 +1360,10 @@ describe("VcsStatusBroadcaster", () => { const next = applyGitStatusStreamEvent(clientStates.at(-1) ?? null, event); clientStates.push(next); yield* Deferred.succeed(subscribed, undefined); - if (next.refName === "repro") yield* Deferred.succeed(checkedOut, undefined); + // The refresh ends with the new branch's remote, after its local update. + if (event._tag === "remoteUpdated" && event.remote && next.refName === "repro") { + yield* Deferred.succeed(checkedOut, undefined); + } }), ).pipe(Effect.forkScoped); yield* Deferred.await(subscribed); @@ -1322,12 +1378,12 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual( clientStates.filter((status) => status.refName === "repro").map((status) => status.pr), - [null], + [null, null], ); // A checkout must not trigger a network fetch. assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues.slice(1), [false]); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("a terminal checkout updates branch-only subscribers without full status", () => @@ -1360,7 +1416,7 @@ describe("VcsStatusBroadcaster", () => { assert.deepEqual(yield* branches, [{ refName: "repro", isRepo: true }]); assert.equal(state.localStatusCalls, 0); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("a checkout read that fails while index.lock is held retries until it succeeds", () => @@ -1415,7 +1471,7 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(checkedOut); assert.strictEqual(state.localStatusCalls, failedCalls + 1); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.scoped), + }), ); it.effect("subscribers share one HEAD watch that ends with the last of them", () => @@ -1457,7 +1513,7 @@ describe("VcsStatusBroadcaster", () => { yield* subscribe; assert.strictEqual(state.headPathCalls, 2); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("a HEAD watch that ended restarts for the next subscriber and keeps earlier ones", () => @@ -1525,7 +1581,7 @@ describe("VcsStatusBroadcaster", () => { yield* checkout("two"); yield* Deferred.await(first.sawRef("two")); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.provide(NodeServices.layer)), ); it.effect("a HEAD watch ends when its git directory is removed", () => @@ -1709,7 +1765,7 @@ it.effect("detail join during invalidation must get fresh totals", () => { yield* Fiber.join(snapshotFiber), Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), ); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("serializes branch reads with detailed refresh publication", () => { const state = newState(); @@ -1735,7 +1791,7 @@ it.effect("serializes branch reads with detailed refresh publication", () => { const result = yield* b.getStatus({ cwd: "/repo" }); assert.equal(result.refName, "new"); assert.equal(state.localStatusCalls, 1); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("publishes overlapping branch reads in checkout order", () => { @@ -1766,7 +1822,7 @@ it.effect("publishes overlapping branch reads in checkout order", () => { { refName: "old", isRepo: true }, { refName: "new", isRepo: true }, ]); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); it.effect("does not replay older queued branches after a new subscriber snapshot", () => { @@ -1799,5 +1855,5 @@ it.effect("does not replay older queued branches after a new subscriber snapshot yield* b.refreshBranchStatus({ cwd: "/repo" }); assert.deepEqual(yield* Queue.take(values), { refName: "latest", isRepo: true }); yield* Fiber.join(subscriber); - }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }).pipe(Effect.provide(layerTestFor(state))); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 99b3a2374162a..28daef7d790ca 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -451,7 +451,30 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); - return yield* refreshLocalStatusCore(cwd); + const local = yield* refreshLocalStatusCore(cwd); + const cached = yield* getCachedStatus(cwd); + // Divergence is local Git data; a slow forge lookup must not delay turn-end updates. + if (cached?.remote?.value?.hasUpstream) { + const divergence = yield* workflow.upstreamDivergence(cwd); + const latest = yield* getCachedStatus(cwd); + if (divergence && latest?.remote?.value && latest.remote.branch === divergence.refName) { + const value = { + ...latest.remote.value, + aheadCount: divergence.aheadCount, + behindCount: divergence.behindCount, + }; + yield* updateCachedRemoteStatus( + cwd, + { + branch: divergence.refName, + value, + fingerprint: fingerprintStatusPart(value), + }, + { publish: true }, + ); + } + } + return local; }); const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* ( @@ -461,7 +484,18 @@ export const make = Effect.gen(function* () { const branch = yield* workflow.currentBranch(cwd); // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch. yield* workflow.invalidateRemoteStatus(cwd); - const value = yield* workflow.remoteStatus({ cwd }, options); + const previousRemote = (yield* getCachedStatus(cwd))?.remote; + const remote = yield* workflow.remoteStatus({ cwd }, options); + const latest = yield* getCachedStatus(cwd); + // An overlapping turn refresh and fetch can both move divergence during the forge lookup. + const refreshed = + remote?.hasUpstream && latest?.remote !== previousRemote && latest?.remote?.branch === branch + ? yield* workflow.upstreamDivergence(cwd) + : null; + const value = + remote && refreshed?.refName === branch + ? { ...remote, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount } + : remote; const currentBranch = yield* workflow.currentBranch(cwd); const cached = yield* getCachedStatus(cwd); if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) { diff --git a/apps/server/src/workspace/IgnorePatterns.test.ts b/apps/server/src/workspace/IgnorePatterns.test.ts new file mode 100644 index 0000000000000..f10345566eca5 --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { parseIgnoreFile } from "./IgnorePatterns.ts"; + +const decide = (contents: string, path: string, isFolder = false) => + parseIgnoreFile(contents).decide(path, isFolder); + +describe("parseIgnoreFile", () => { + it("lets the last matching pattern decide, including negations", () => { + expect(decide("*keep*\n!*keep*\n", "sub/keep-link.ts")).toBe("included"); + expect(decide("!*keep*\n*keep*\n", "sub/keep-link.ts")).toBe("ignored"); + expect(decide("# comment\n\nother\n", "keep.ts")).toBeUndefined(); + }); + + it("anchors patterns that contain a slash and matches bare names at any depth", () => { + expect(decide("link", "a/b/link")).toBe("ignored"); + expect(decide("/link", "a/link")).toBeUndefined(); + expect(decide("/link", "link")).toBe("ignored"); + expect(decide("a/link", "x/a/link")).toBeUndefined(); + expect(decide("a/*.ts", "a/b/c.ts")).toBeUndefined(); + expect(decide("link", "blink")).toBeUndefined(); + expect(decide("link", "a/blink")).toBeUndefined(); + }); + + it("supports globstars, classes, escapes, and folder-only patterns", () => { + expect(decide("**/gen/*.ts", "gen/a.ts")).toBe("ignored"); + expect(decide("a/**/b", "a/x/y/b")).toBe("ignored"); + expect(decide("a/**/b", "a/b")).toBe("ignored"); + expect(decide("foo/**/bar", "foo/xbar")).toBeUndefined(); + expect(decide("foo/**/bar", "foo/x/ybar")).toBeUndefined(); + expect(decide("out/**", "out/x/y")).toBe("ignored"); + expect(decide("link-[0-9]", "link-7")).toBe("ignored"); + expect(decide("link-[!0-9]", "link-7")).toBeUndefined(); + expect(decide("link-?", "link-/")).toBeUndefined(); + expect(decide("\\!bang\n\\#hash\nstar\\*", "!bang")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "#hash")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "starx")).toBeUndefined(); + expect(decide("dist/", "dist")).toBeUndefined(); + expect(decide("dist/", "dist", true)).toBe("ignored"); + }); + + it("matches adversarial patterns in linear time", () => { + // A backtracking regex takes seconds to reject this pair; the vitest timeout catches that. + const pattern = `${"a*".repeat(20)}b\n`; + expect(decide(pattern, `${"a".repeat(200)}c`)).toBeUndefined(); + expect(decide(pattern.repeat(50), `${"a".repeat(1_000)}c`)).toBeUndefined(); + expect(decide(pattern, `${"a".repeat(200)}b`)).toBe("ignored"); + }); + + it("parses unclosed classes in linear time", () => { + // Rescanning the rest of the line for each `[` stalls for over a minute here; linear takes ms. + expect(decide("[".repeat(30_000), "[".repeat(30_000))).toBe("ignored"); + expect(decide(`${"[".repeat(30_000)}]`, "x")).toBeUndefined(); + expect(decide("[a][", "a[")).toBe("ignored"); + }); +}); diff --git a/apps/server/src/workspace/IgnorePatterns.ts b/apps/server/src/workspace/IgnorePatterns.ts new file mode 100644 index 0000000000000..1180b02316ef9 --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.ts @@ -0,0 +1,170 @@ +/** + * Gitignore-syntax matching for `.ignore` files, which git cannot evaluate for us. Patterns come + * from the repository, so each runs as an NFA over the path (O(pattern × path)): a backtracking + * regex stalls for seconds on `a*a*a*…b`. POSIX `[:class:]` names are not supported. + */ + +type Token = + | { readonly type: "char"; readonly char: string } + | { readonly type: "one" } + | { readonly type: "class"; readonly negated: boolean; readonly ranges: ReadonlyArray } + | { readonly type: "star" } + | { readonly type: "any" } + /** A leading or inner `**` segment: nothing, or anything ending in `/`. */ + | { readonly type: "folders" }; + +interface Pattern { + readonly tokens: ReadonlyArray; + readonly negated: boolean; + readonly folderOnly: boolean; +} + +export type IgnoreDecision = "ignored" | "included"; + +function parseClass(chars: ReadonlyArray, start: number) { + let index = start + 1; + const negated = chars[index] === "!" || chars[index] === "^"; + if (negated) index += 1; + const ranges: string[] = []; + for (let first = true; index < chars.length; first = false) { + let char = chars[index]!; + if (char === "]" && !first) + return { token: { type: "class", negated, ranges } as const, end: index }; + if (char === "\\" && index + 1 < chars.length) char = chars[++index]!; + if (chars[index + 1] === "-" && index + 2 < chars.length && chars[index + 2] !== "]") { + let last = chars[index + 2]!; + index += 2; + if (last === "\\" && index + 1 < chars.length) last = chars[++index]!; + ranges.push(char, last); + } else { + ranges.push(char, char); + } + index += 1; + } + return undefined; +} + +function parseLine(rawLine: string): Pattern | undefined { + let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine; + // Trailing spaces are dropped unless escaped. + while (line.endsWith(" ") && !line.endsWith("\\ ")) line = line.slice(0, -1); + if (line === "" || line.startsWith("#")) return undefined; + const negated = line.startsWith("!"); + if (negated) line = line.slice(1); + else if (line.startsWith("\\!") || line.startsWith("\\#")) line = line.slice(1); + const folderOnly = line.endsWith("/") && !line.endsWith("\\/"); + if (folderOnly) line = line.slice(0, -1); + if (line === "") return undefined; + const anchored = line.slice(0, -1).includes("/"); + if (line.startsWith("/")) line = line.slice(1); + + const chars = Array.from(line); + const tokens: Token[] = anchored ? [] : [{ type: "folders" }]; + // A `[` that never closes leaves every later `[` unclosed too, so one failed scan settles them + // all; rescanning the suffix for each would make `[[[[…` quadratic. + let classesClose = true; + for (let index = 0; index < chars.length; index += 1) { + const char = chars[index]!; + if (char === "*" && chars[index + 1] === "*") { + const atSegmentStart = index === 0 || chars[index - 1] === "/"; + const next = chars[index + 2]; + if (atSegmentStart && next === "/") { + tokens.push({ type: "folders" }); + index += 2; + continue; + } + if (atSegmentStart && next === undefined) { + tokens.push({ type: "any" }); + index += 1; + continue; + } + } + if (char === "*") tokens.push({ type: "star" }); + else if (char === "?") tokens.push({ type: "one" }); + else if (char === "[") { + const parsed = classesClose ? parseClass(chars, index) : undefined; + if (!parsed) classesClose = false; + if (parsed) { + tokens.push(parsed.token); + index = parsed.end; + } else tokens.push({ type: "char", char }); + } else if (char === "\\" && index + 1 < chars.length) { + tokens.push({ type: "char", char: chars[++index]! }); + } else tokens.push({ type: "char", char }); + } + return { tokens, negated, folderOnly }; +} + +/** + * States are token positions. A `folders` token that has consumed part of a segment is `~position` + * instead: it may only finish after the next `/`, so an inner globstar never matches `xbar` as `bar`. + */ +function matches(tokens: ReadonlyArray, path: ReadonlyArray): boolean { + let states = new Set(); + const add = (set: Set, position: number) => { + // Wildcards also match nothing, so reaching one reaches the token after it. + for (; position <= tokens.length && !set.has(position); position += 1) { + set.add(position); + const type = tokens[position]?.type; + if (type !== "star" && type !== "any" && type !== "folders") return; + } + }; + add(states, 0); + for (const char of path) { + const next = new Set(); + for (const state of states) { + const position = state < 0 ? ~state : state; + const token = tokens[position]; + if (!token) continue; + switch (token.type) { + case "char": + if (token.char === char) add(next, position + 1); + break; + case "one": + if (char !== "/") add(next, position + 1); + break; + case "class": { + let inRange = false; + for (let index = 0; index < token.ranges.length && !inRange; index += 2) { + inRange = token.ranges[index]! <= char && char <= token.ranges[index + 1]!; + } + if (char !== "/" && inRange !== token.negated) add(next, position + 1); + break; + } + case "star": + if (char !== "/") add(next, position); + break; + case "any": + add(next, position); + break; + case "folders": + if (char === "/") add(next, position); + else next.add(~position); + break; + } + } + if (next.size === 0) return false; + states = next; + } + return states.has(tokens.length); +} + +export interface IgnoreFile { + /** The last pattern that matches decides; `undefined` when none does. */ + readonly decide: (relativePath: string, isFolder: boolean) => IgnoreDecision | undefined; +} + +export function parseIgnoreFile(contents: string): IgnoreFile { + const patterns = contents.split("\n").flatMap((line) => parseLine(line) ?? []); + return { + decide: (relativePath, isFolder) => { + const path = Array.from(relativePath); + for (let index = patterns.length - 1; index >= 0; index -= 1) { + const pattern = patterns[index]!; + if (pattern.folderOnly && !isFolder) continue; + if (matches(pattern.tokens, path)) return pattern.negated ? "included" : "ignored"; + } + return undefined; + }, + }; +} diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 5db1b2e14870a..92d5285453270 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -433,6 +433,20 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); }), ); + + it.effect("finds ignored files that sort past the listing limit", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ git: true }); + yield* writeTextFile(cwd, ".gitignore", "*.secret\n"); + for (let index = 1; index <= 205; index += 1) { + yield* writeTextFile(cwd, `file-${String(index).padStart(3, "0")}.secret`, "s"); + } + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const listed = yield* workspaceEntries.listIgnoredFiles({ cwd, query: "file-205" }); + expect(listed.files).toContainEqual({ path: "file-205.secret", byteLength: 1 }); + }), + ); }); describe("search", () => { @@ -532,6 +546,133 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); + it.effect("indexes symlinked files and directories inside the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "index-link.ts")); + const symlinkEntries = [ + { kind: "directory", path: "src-link" }, + { kind: "file", path: "index-link.ts" }, + ]; + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entry of symlinkEntries) { + expect(searched.entries).toContainEqual(expect.objectContaining(entry)); + expect(listed.entries).toContainEqual(expect.objectContaining(entry)); + } + }), + ); + it.effect("skips symlinks that ignore rules hide or that leave the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const outside = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-outside-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".ignore", "custom-link\n"); + yield* fileSystem.symlink("src", path.join(cwd, "custom-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "tracked-link.ts")); + yield* fileSystem.symlink("src", path.join(cwd, "ignored-link")); + yield* fileSystem.symlink("src", path.join(cwd, "kept-link")); + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + yield* git(cwd, ["add", "tracked-link.ts"]); + yield* writeTextFile(cwd, ".gitignore", "tracked-link.ts\nignored-link\n"); + // A submodule path makes `git check-ignore` refuse the whole batch without --no-index. + const submodule = path.join(cwd, "vendor/sub"); + yield* writeTextFile(submodule, "a.ts", "export {};"); + yield* git(submodule, ["init"]); + yield* git(submodule, ["add", "a.ts"]); + yield* git(submodule, [ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-m", + "init", + ]); + yield* git(cwd, ["add", "vendor/sub"]); + yield* fileSystem.symlink("a.ts", path.join(submodule, "sublink.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("kept-link"); + expect(paths).toContain("vendor/sub/sublink.ts"); + expect(paths).not.toContain("custom-link"); + expect(paths).not.toContain("tracked-link.ts"); + expect(paths).not.toContain("ignored-link"); + expect(paths).not.toContain("outside-link"); + } + }), + ); + it.effect("lets the nearest .ignore rule decide a symlink, and git's rules still hide it", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, ".gitignore", "*keep*\n"); + yield* writeTextFile(cwd, ".ignore", "!*keep*\n*hide*\n"); + yield* writeTextFile(cwd, "sub/.ignore", "!*hide*\n"); + yield* writeTextFile(cwd, "keep-real.ts", "export {};"); + yield* writeTextFile(cwd, "sub/hide-real.ts", "export {};"); + yield* fileSystem.symlink("keep-real.ts", path.join(cwd, "keep-link.ts")); + yield* fileSystem.symlink("hide-real.ts", path.join(cwd, "sub/hide-link.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("sub/hide-link.ts"); + expect(paths).not.toContain("keep-link.ts"); + } + // The real files are shown or hidden by the same rules. + const listedPaths = listed.entries.map((entry) => entry.path); + expect(listedPaths).toContain("sub/hide-real.ts"); + expect(listedPaths).not.toContain("keep-real.ts"); + }), + ); + it.effect("matches .ignore rules against whole names and treats folder links as links", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".gitignore", "blink\n"); + // `!link` must not re-include `blink`, and `folder-link/` does not apply to a link. + yield* writeTextFile(cwd, ".ignore", "!link\nfolder-link/\n"); + yield* fileSystem.symlink("src", path.join(cwd, "blink")); + yield* fileSystem.symlink("src", path.join(cwd, "folder-link")); + yield* writeTextFile(cwd, "sub/blink", "regular"); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).not.toContain("blink"); + expect(paths).not.toContain("sub/blink"); + expect(paths).toContain("folder-link"); + } + }), + ); it.effect("finds a path inside a gitignored nested git worktree only by its exact path", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-worktree-", git: true }); diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index cac706f7ca4a2..43c8fae4dfcaf 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -576,9 +576,13 @@ export const make = Effect.gen(function* () { }) .pipe(Effect.orElseSucceed(() => undefined)); if (!result || result.exitCode !== 0) return { files: [], truncated: false }; + // Filter before the cap so files sorting past it stay reachable by search. + const query = input.query?.toLowerCase() ?? ""; const paths = result.stdout .split("\0") - .filter((entry) => entry.length > 0 && !entry.endsWith("/")) + .filter( + (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query), + ) .toSorted(); const files = yield* Effect.promise(() => Promise.all( diff --git a/apps/server/src/workspace/WorkspaceFinderProcess.ts b/apps/server/src/workspace/WorkspaceFinderProcess.ts index f5c67bf6c7358..78f715c7abb4d 100644 --- a/apps/server/src/workspace/WorkspaceFinderProcess.ts +++ b/apps/server/src/workspace/WorkspaceFinderProcess.ts @@ -3,16 +3,27 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeModule from "node:module"; import * as NodeSea from "node:sea"; -import type { FileFinder, InitOptions, Result } from "@ff-labs/fff-node"; +import type { + FileFinder, + InitOptions, + Result, + WatchEvent, + WatchUnsubscribe, +} from "@ff-labs/fff-node"; import * as Context from "effect/Context"; type FinderMethod = | "destroy" | "directorySearch" + | "directorySearchAsync" | "fileSearch" + | "fileSearchAsync" + | "getScanProgressAsync" | "grep" + | "grepAsync" | "isScanning" | "mixedSearch" + | "mixedSearchAsync" | "scanFiles" | "scanFilesAsync" | "waitForIndexReady"; @@ -22,6 +33,9 @@ export interface ProcessFinder { method: Method, ...args: Parameters ) => Promise>>; + readonly watch: ( + onBatch: (events: ReadonlyArray) => void, + ) => Promise>; readonly close: () => Promise; } @@ -37,9 +51,20 @@ process.once("message", (options) => { process.send({ created: created.ok ? { ok: true } : created }); if (!created.ok) return; const finder = created.value; + let unwatch; process.on("message", async ({ id, method, args }) => { try { - process.send({ id, value: await finder[method](...args) }); + if (method === "watch") { + const watched = finder.watch((events) => process.send({ events })); + if (watched.ok) unwatch = watched.value; + process.send({ id, value: watched.ok ? { ok: true } : watched }); + } else if (method === "unwatch") { + unwatch?.(); + unwatch = undefined; + process.send({ id }); + } else { + process.send({ id, value: await finder[method](...args) }); + } } catch (cause) { process.send({ id, failed: true, cause }); } @@ -48,6 +73,7 @@ process.once("message", (options) => { `; type FinderMessage = + | { readonly events: ReadonlyArray } | { readonly created: Result } | { readonly id: number; readonly value: unknown } | { readonly id: number; readonly failed: true; readonly cause: unknown }; @@ -83,6 +109,7 @@ const openProcessFinder: OpenFinder = (options) => { readonly resolve: (value: never) => void; readonly reject: (cause: unknown) => void } >(); let nextId = 0; + let onWatchBatch: ((events: ReadonlyArray) => void) | undefined; let failure: unknown; const fail = (cause: unknown) => { failure ??= cause; @@ -96,8 +123,8 @@ const openProcessFinder: OpenFinder = (options) => fail(new Error(`The fff process exited with ${signal ?? `code ${code}`}.`)), ); - const call: ProcessFinder["call"] = (method, ...args) => - new Promise((resolveCall, rejectCall) => { + const request = (method: string, args: ReadonlyArray) => + new Promise((resolveCall, rejectCall) => { if (failure !== undefined) { rejectCall(failure); return; @@ -110,6 +137,10 @@ const openProcessFinder: OpenFinder = (options) => }); child.on("message", (message: FinderMessage) => { + if ("events" in message) { + onWatchBatch?.(message.events); + return; + } if ("created" in message) { if (!message.created.ok) { resolve(message.created); @@ -119,7 +150,19 @@ const openProcessFinder: OpenFinder = (options) => resolve({ ok: true, value: { - call, + call: (method, ...args) => request(method, args), + watch: async (onBatch) => { + onWatchBatch = onBatch; + const result = (await request("watch", [])) as Result; + if (!result.ok) return result; + return { + ok: true, + value: () => { + onWatchBatch = undefined; + void request("unwatch", []).catch(() => undefined); + }, + }; + }, close: () => { child.kill(); return exited; @@ -128,11 +171,11 @@ const openProcessFinder: OpenFinder = (options) => }); return; } - const request = pending.get(message.id); - if (!request) return; + const pendingRequest = pending.get(message.id); + if (!pendingRequest) return; pending.delete(message.id); - if ("failed" in message) request.reject(message.cause); - else request.resolve(message.value as never); + if ("failed" in message) pendingRequest.reject(message.cause); + else pendingRequest.resolve(message.value as never); }); child.send(options, (error) => { if (error) fail(error); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 723ba9ad14690..e164e0d90b902 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -4,14 +4,18 @@ import { type GrepCursor, type GrepOptions, type GrepResult, + type WatchEvent, } from "@ff-labs/fff-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { afterEach, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -30,6 +34,7 @@ const withInProcessFinder = (finder: FileFinder) => value: { call: async (method, ...args) => (finder[method] as (...input: typeof args) => never)(...args), + watch: async (onBatch) => finder.watch(onBatch), close: async () => undefined, }, })); @@ -86,7 +91,7 @@ it.effect("filters image searches before applying the result limit", () => ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)), fileItem("public/icon.svg"), ]; - const fileSearch = vi.fn(() => ({ + const fileSearch = vi.fn(async () => ({ ok: true as const, value: { items, @@ -98,7 +103,12 @@ it.effect("filters image searches before applying the result limit", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: fileSearch, } as unknown as FileFinder; const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project").pipe( withInProcessFinder(finder), @@ -132,7 +142,7 @@ it.effect("fetches past a first page of Git-ignored results", () => fileItem("hidden/c.ts"), fileItem("src/a.ts"), ]; - const fileSearch = vi.fn((_query: string, options?: { pageSize?: number }) => ({ + const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({ ok: true as const, value: { items: items.slice(0, options?.pageSize), @@ -144,7 +154,12 @@ it.effect("fetches past a first page of Git-ignored results", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: fileSearch, } as unknown as FileFinder; const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(withInProcessFinder(finder)); const result = yield* searchIndex.search("a", 1, "file", false); @@ -164,7 +179,12 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch: vi.fn(() => ({ + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: vi.fn(async () => ({ ok: true as const, value: { items, scores: [], totalMatched: 1, totalFiles: 1 }, })), @@ -215,7 +235,7 @@ it.effect("continues whole-word searches after a filtered grep page", () => filteredFileCount: 1, nextCursor: cursor, }); - const grep = vi.fn((_query: string, options?: GrepOptions) => + const grep = vi.fn(async (_query: string, options?: GrepOptions) => options?.cursor ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) } : { @@ -226,7 +246,12 @@ it.effect("continues whole-word searches after a filtered grep page", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - grep, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + grepAsync: grep, } as unknown as FileFinder; const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content").pipe( withInProcessFinder(finder), @@ -256,6 +281,250 @@ it.effect("continues whole-word searches after a filtered grep page", () => ).pipe(Effect.provide(testLayer)), ); +function fakeSymlinkFinder( + directories: ReadonlyArray, + options: { + readonly indexed?: ReadonlyArray<{ + readonly path: string; + readonly kind: "file" | "directory"; + }>; + readonly watchFailures?: number; + } = {}, +) { + const watchers: Array<(events: ReadonlyArray) => void> = []; + let watchFailures = options.watchFailures ?? 0; + // fff's pageIndex is an offset into the results, not a page number. + const directorySearch = vi.fn( + async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => { + const offset = searchOptions?.pageIndex ?? 0; + const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100)); + return { + ok: true as const, + value: { + items: items.map((relativePath) => ({ relativePath })), + totalMatched: directories.length, + }, + }; + }, + ); + const indexedItems = (options.indexed ?? []).map((entry) => ({ + type: entry.kind, + item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) }, + })); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + // fff's isScanning waits on the picker lock on the JS thread. + isScanning: () => { + throw new Error("isScanning must not run on the JS thread"); + }, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: (callback: (events: ReadonlyArray) => void) => { + if (watchFailures > 0) { + watchFailures -= 1; + throw new Error("File system watcher is not ready"); + } + watchers.push(callback); + return { ok: true as const, value: () => undefined }; + }, + directorySearchAsync: directorySearch, + fileSearchAsync: async () => { + const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : [])); + return { ok: true as const, value: { items, scores: [], totalMatched: items.length } }; + }, + mixedSearchAsync: async () => ({ + ok: true as const, + value: { items: indexedItems, totalMatched: indexedItems.length }, + }), + } as unknown as FileFinder; + return { + withFinder: withInProcessFinder(finder), + directorySearch, + notifyWatchers: (events: ReadonlyArray) => + watchers.forEach((watcher) => watcher(events)), + }; +} + +const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) => + searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path))); + +it.effect("reads symlinks again after the watcher reports a change", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { directorySearch, notifyWatchers, withFinder } = fakeSymlinkFinder([]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(withFinder); + const concurrent = yield* Effect.all( + Array.from({ length: 8 }, () => listedPaths(searchIndex)), + { concurrency: "unbounded" }, + ); + yield* fileSystem.remove(path.join(cwd, "old-link.ts")); + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + const beforeNotice = yield* listedPaths(searchIndex); + // Editing a file cannot move a link, so it does not cost a rescan. + notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]); + const afterEdit = yield* listedPaths(searchIndex); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const afterNotice = yield* listedPaths(searchIndex); + // fff reports a link replaced in place as modified. + yield* fileSystem.remove(path.join(cwd, "new-link.ts")); + yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]); + const afterReplace = yield* listedPaths(searchIndex); + + expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"])); + expect(beforeNotice).toEqual(["old-link.ts"]); + expect(afterEdit).toEqual(["old-link.ts"]); + expect(afterNotice).toEqual(["new-link.ts"]); + expect(afterReplace).toEqual([]); + expect(directorySearch).toHaveBeenCalledTimes(3); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("answers from the last symlink scan while a slow rescan runs", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { notifyWatchers, withFinder } = fakeSymlinkFinder([]); + // Holding git's ignore check open keeps the rescan from finishing. + const gate = yield* Deferred.make(); + let holdIgnoreChecks = false; + const vcsProcess = yield* VcsProcess.VcsProcess; + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe( + withFinder, + Effect.provideService(VcsProcess.VcsProcess, { + ...vcsProcess, + run: (input) => + holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored" + ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input))) + : vcsProcess.run(input), + }), + ); + expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]); + + holdIgnoreChecks = true; + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex)); + yield* TestClock.adjust("1 second"); + expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]); + + yield* Deferred.succeed(gate, undefined); + expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("keeps symlinks once the watcher subscribes after starting late", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts")); + const { directorySearch, withFinder } = fakeSymlinkFinder([], { watchFailures: 2 }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(withFinder); + const scansAfterRound: number[] = []; + for (let round = 0; round < 5; round += 1) { + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + scansAfterRound.push(directorySearch.mock.calls.length); + yield* TestClock.adjust("1 minute"); + } + + // An unwatched scan serves reads only briefly; the third has a watcher and is kept. + expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect( + "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones", + () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "src")); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + // A link the scan rejects stays out even when the watcher indexed it. + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + const { withFinder } = fakeSymlinkFinder([], { + indexed: [ + { path: "outside-link", kind: "file" }, + { path: "src-link", kind: "file" }, + { path: "link-file.ts", kind: "file" }, + ], + }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(withFinder); + const searched = yield* searchIndex.search("link", 10); + const files = yield* searchIndex.search("link", 1, "file"); + const listed = yield* searchIndex.list(); + + expect(searched.entries).toEqual([ + { path: "src-link", kind: "directory" }, + { path: "link-file.ts", kind: "file" }, + ]); + // The dropped link does not take the only slot. + expect(files).toEqual({ + entries: [{ path: "link-file.ts", kind: "file" }], + truncated: false, + }); + expect(listed.entries).toEqual([ + { path: "link-file.ts", kind: "file" }, + { path: "src-link", kind: "directory" }, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("finds symlinks in folders past the first page of the index", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "late")); + yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts")); + // Folders fff lists but that are gone by the time they are read are skipped. + const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`); + const { directorySearch, withFinder } = fakeSymlinkFinder([...firstPage, "late"]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(withFinder); + + expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]); + expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([ + 0, 1_000, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + // fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "refuses to index a workspace rooted at the home directory", diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 4432091a2e82b..05e61933f7e1a 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,8 +1,24 @@ -import type { DirItem, FileItem, GrepCursor, MixedItem, Result } from "@ff-labs/fff-node"; +// @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child +import * as NodeFSP from "node:fs/promises"; + +import type { + DirItem, + FileItem, + GrepCursor, + MixedItem, + Result, + WatchEvent, + WatchUnsubscribe, +} from "@ff-labs/fff-node"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as LayerMap from "effect/LayerMap"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import type { @@ -15,9 +31,11 @@ import type { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; +import { scoreSubsequenceMatch } from "@t3tools/shared/searchRanking"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { type ProcessFinder, WorkspaceFinderOpener } from "./WorkspaceFinderProcess.ts"; +import { type IgnoreDecision, type IgnoreFile, parseIgnoreFile } from "./IgnorePatterns.ts"; const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2; @@ -26,6 +44,13 @@ const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000; const WORKSPACE_INDEX_IDLE_TTL = "15 minutes"; const CONTENT_SEARCH_TIME_BUDGET_MS = 250; const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100; +const SYMLINK_SCAN_CONCURRENCY = 16; +// A scan no watcher can invalidate is reused this long, so typing does not rescan every folder. +const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000; +// A rescan that outlasts this leaves the read on the previous scan. +const SYMLINK_RESCAN_WAIT = "5 millis"; +// Each page is a synchronous native call; small pages let searches run between them. +const SYMLINK_DIRECTORY_PAGE_SIZE = 1_000; export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError()( "WorkspaceSearchIndexCreateFailed", @@ -278,6 +303,135 @@ function withDirectoryAncestors(entries: ReadonlyArray): ProjectEn return [...entryByPath.values()]; } +interface ScannedDirectory { + readonly directory: string; + readonly links: ReadonlyArray; + /** Every symlink in the folder, including ones dropped for leaving the workspace. */ + readonly linkPaths: ReadonlyArray; + /** A nested repository (or the workspace's own), whose ignore rules own what is below it. */ + readonly isRepository: boolean; + readonly ignoreFile: string | undefined; +} + +const joinEntryPath = (directory: string, name: string) => + directory ? `${directory}/${name}` : name; + +/** + * fff skips symlinks, and `followSymlinks` drops file links, dedupes folder links, and walks out + * of the workspace. So links are read from the folders fff already indexed (ignore rules applied), + * without descending into them, and kept only when they resolve inside the workspace. + */ +const scanDirectory = Effect.fn("WorkspaceSearchIndex.scanDirectory")(function* ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + cwd: string, + root: string, + directory: string, +) { + // Effect's readDirectory returns bare names; one lstat per child would cost far more. + const children = yield* Effect.promise(() => + NodeFSP.readdir(path.join(cwd, directory), { withFileTypes: true }).catch(() => []), + ); + const links: ProjectEntry[] = []; + const linkPaths: string[] = []; + let isRepository = false; + let ignoreFile: string | undefined; + for (const child of children) { + if (child.name === ".git") isRepository = true; + if (child.name === ".ignore" && child.isFile()) { + ignoreFile = yield* fileSystem + .readFileString(path.join(cwd, directory, child.name)) + .pipe(Effect.orElseSucceed(() => undefined)); + } + if (!child.isSymbolicLink()) continue; + const entryPath = joinEntryPath(directory, child.name); + linkPaths.push(entryPath); + const absolutePath = path.join(cwd, entryPath); + const target = yield* Effect.all([ + fileSystem.realPath(absolutePath), + fileSystem.stat(absolutePath), + ]).pipe(Effect.orElseSucceed(() => undefined)); + if (!target) continue; + const relative = path.relative(root, target[0]); + if ( + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) || + relative.split(path.sep).includes(".git") || + (target[1].type !== "Directory" && target[1].type !== "File") + ) { + continue; + } + links.push({ path: entryPath, kind: target[1].type === "Directory" ? "directory" : "file" }); + } + return { directory, links, linkPaths, isRepository, ignoreFile } satisfies ScannedDirectory; +}); + +/** Whether `entryPath` is `directory` itself or below it. */ +const isWithin = (entryPath: string, directory: string) => + directory === "" || entryPath.startsWith(`${directory}/`); + +/** + * fff reads `.ignore` files alongside git's rules, and like ripgrep the nearest one that matches + * decides, ahead of any `.gitignore`. `ignoreFiles` is ordered deepest folder first. + */ +function decideByIgnoreFiles( + entry: ProjectEntry, + ignoreFiles: ReadonlyArray<{ readonly directory: string; readonly file: IgnoreFile }>, +): IgnoreDecision | undefined { + for (const { directory, file } of ignoreFiles) { + if (!isWithin(entry.path, directory) || entry.path === directory) continue; + const relative = directory ? entry.path.slice(directory.length + 1) : entry.path; + // Like git and ripgrep, a link is never a folder to a folder-only rule, whatever it targets. + const decision = file.decide(relative, false); + if (decision) return decision; + } + return undefined; +} + +/** Places each symlink before the first index result that matches the query less closely. */ +function mergeSymlinkMatches( + indexed: ProjectSearchEntriesResult, + linkPaths: ReadonlySet, + symlinks: ReadonlyArray, + query: string, + limit: number, +): ProjectSearchEntriesResult { + if (linkPaths.size === 0) return indexed; + // fff's watcher indexes links created after its scan, under a kind of its own choosing, so a + // path it already returned takes the link's kind (or drops out of a kind-filtered search). + const symlinkByPath = new Map(symlinks.map((entry) => [entry.path, entry])); + const score = (entry: ProjectEntry) => + scoreSubsequenceMatch(entry.path.toLowerCase(), query) ?? Number.POSITIVE_INFINITY; + const indexedPaths = new Set(indexed.entries.map((entry) => entry.path)); + const pending = symlinks + .flatMap((entry) => { + const entryScore = score(entry); + return Number.isFinite(entryScore) && !indexedPaths.has(entry.path) + ? [{ entry, score: entryScore }] + : []; + }) + .toSorted((left, right) => left.score - right.score); + const entries: ProjectEntry[] = []; + let nextPending = 0; + for (const indexedEntry of indexed.entries) { + const entry = linkPaths.has(indexedEntry.path) + ? symlinkByPath.get(indexedEntry.path) + : indexedEntry; + if (!entry) continue; + const entryScore = score(entry); + while (nextPending < pending.length && pending[nextPending]!.score < entryScore) { + entries.push(pending[nextPending++]!.entry); + } + entries.push(entry); + } + for (; nextPending < pending.length; nextPending += 1) entries.push(pending[nextPending]!.entry); + return { + entries: entries.slice(0, limit), + truncated: indexed.truncated || entries.length > limit, + }; +} + // fff applies .gitignore files only; Git also ignores paths from .git/info/exclude and the global excludes file. const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths")(function* ( vcsProcess: VcsProcess.VcsProcess["Service"], @@ -390,6 +544,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( variant: WorkspaceSearchIndexVariant = "paths", ) { const hostIsWindows = yield* HostProcess.isWindows; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) => Effect.tryPromise({ try: () => finder.call("destroy").finally(finder.close), @@ -419,20 +575,16 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }), ); - const hasIncompleteInitialScan = () => - initialScanTimedOut - ? Effect.tryPromise({ - try: () => finder.call("isScanning"), - catch: (cause) => - new WorkspaceSearchIndexSearchFailed({ - cwd, - queryLength: 0, - pageSize: 0, - reason: "FileFinder.isScanning threw unexpectedly.", - cause, - }), - }) - : Effect.succeed(false); + // fff's isScanning takes the picker lock too, so progress is read off the JS thread. + const isScanning = Effect.promise(async () => { + try { + const progress = await finder.call("getScanProgressAsync"); + return !progress.ok || progress.value.isScanning; + } catch { + return true; + } + }); + const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false)); const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, @@ -440,6 +592,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", execute: () => Promise>, ): Effect.fn.Return { + // fff's searches wait on its picker lock, which its watcher can hold for minutes. const result = yield* Effect.tryPromise({ try: execute, catch: (cause) => @@ -447,7 +600,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( cwd, queryLength: query.length, pageSize, - reason: `FileFinder.${operation} threw unexpectedly.`, + reason: `FileFinder.${operation} rejected unexpectedly.`, cause, }), }); @@ -462,6 +615,227 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( return result.value; }); + const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + + const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")( + function* () { + const directories: string[] = []; + // fff's pageIndex is an offset into the results, not a page number. + for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) { + const result = yield* Effect.promise(async () => { + try { + return await finder.call("directorySearchAsync", "", { + pageIndex, + pageSize: SYMLINK_DIRECTORY_PAGE_SIZE, + }); + } catch { + return undefined; + } + }); + if (!result?.ok) return directories; + for (const item of result.value.items) { + const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows)); + if (directory) directories.push(directory); + } + if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories; + } + }, + ); + + /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */ + const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* ( + repository: string, + entries: ReadonlyArray, + ) { + const relativePaths = entries.map((entry) => + repository ? entry.path.slice(repository.length + 1) : entry.path, + ); + const repositoryCwd = path.join(cwd, repository); + const result = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + // fff applies ignore rules to tracked paths too, so the index is not consulted. + args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"], + cwd: repositoryCwd, + stdin: `${relativePaths.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 10_000, + maxOutputBytes: 16 * 1024 * 1024, + }) + .pipe(Effect.orElseSucceed(() => undefined)); + // Exit 1 means nothing matched. + if (result?.exitCode === 1) return []; + if (result?.exitCode !== 0 || result.stdoutTruncated) { + // Outside git no rules apply (git exits before reading stdin, so the cause is lost). + // Any other failure hides the repository's links rather than leaking ones it ignores. + const insideRepository = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + args: ["rev-parse", "--git-dir"], + cwd: repositoryCwd, + timeoutMs: 10_000, + }) + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + return insideRepository ? entries.map((entry) => entry.path) : []; + } + return result.stdout + .split("\0") + .filter(Boolean) + .map((relativePath) => (repository ? `${repository}/${relativePath}` : relativePath)); + }); + + const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () { + const indexComplete = !(yield* isScanning); + const directories = yield* listIndexedDirectories(); + const scanned = yield* Effect.forEach( + ["", ...directories], + (directory) => scanDirectory(fileSystem, path, cwd, root, directory), + { concurrency: SYMLINK_SCAN_CONCURRENCY }, + ); + const candidates = scanned.flatMap((directory) => directory.links); + const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths)); + if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete }; + + const ignoreFiles = scanned + .flatMap(({ directory, ignoreFile }) => + ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }], + ) + .toSorted((left, right) => right.directory.length - left.directory.length); + const decisions = new Map( + candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]), + ); + const repositories = [ + "", + ...scanned.flatMap(({ directory, isRepository }) => + isRepository && directory ? [directory] : [], + ), + ].toSorted((left, right) => right.length - left.length); + const entriesByRepository = Map.groupBy( + candidates.filter((entry) => decisions.get(entry.path) === undefined), + (entry) => + repositories.find( + (repository) => isWithin(entry.path, repository) && entry.path !== repository, + ) ?? "", + ); + const ignored = new Set( + (yield* Effect.forEach( + entriesByRepository, + ([repository, entries]) => listGitIgnored(repository, entries), + { concurrency: 4 }, + )).flat(), + ); + return { + entries: candidates.filter((entry) => + decisions.get(entry.path) === undefined + ? !ignored.has(entry.path) + : decisions.get(entry.path) === "included", + ), + linkPaths, + indexComplete, + }; + }); + + // One scan runs at a time and outlives the reads that started it. Only the first read waits for + // it in full: after that a change or expiry marks the result stale, and reads wait briefly for + // the rescan before answering from the last finished one, so file churn cannot stall search. + type SymlinkScan = Effect.Success>; + let lastSymlinkScan: SymlinkScan | undefined; + let lastSymlinkScanExpiresAt: number | undefined; + let pendingSymlinkScan: Deferred.Deferred | undefined; + let symlinkScanStale = false; + let knownLinkPaths: ReadonlySet = new Set(); + const invalidateSymlinkScan = () => { + symlinkScanStale = true; + }; + const isKnownLink = (absolutePath: string) => + [cwd, root].some((base) => + knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)), + ); + const onWatchBatch = (events: ReadonlyArray) => { + // fff reports a link replaced in place as `modified`, so edits to known links count too. + const editsOnly = events.every( + (event) => + event.kind === "modified" && + !/(^|[\\/])\.(git)?ignore$/.test(event.path) && + !isKnownLink(event.path), + ); + if (!editsOnly) invalidateSymlinkScan(); + }; + // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so + // each read retries until one is in place. + let unwatch: WatchUnsubscribe | undefined; + yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.())); + const ensureWatching = async () => { + if (unwatch) return true; + try { + const result = await finder.watch(onWatchBatch); + if (result.ok) unwatch = result.value; + } catch { + // Not ready yet; the next read tries again. + } + return unwatch !== undefined; + }; + const indexScope = yield* Effect.scope; + const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () { + symlinkScanStale = false; + const done = yield* Deferred.make(); + pendingSymlinkScan = done; + // Subscribing before the scan starts means no change during it goes unseen. + const watched = yield* Effect.promise(ensureWatching); + yield* scanSymlinkEntries().pipe( + Effect.tap((result) => + Effect.gen(function* () { + lastSymlinkScan = result; + knownLinkPaths = result.linkPaths; + // Without a watcher, or before fff has seen every folder, the result is kept only briefly. + lastSymlinkScanExpiresAt = + watched && result.indexComplete + ? undefined + : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS; + }), + ), + Effect.onExit((exit) => + Effect.sync(() => { + pendingSymlinkScan = undefined; + }).pipe(Effect.andThen(Deferred.done(done, exit))), + ), + Effect.forkIn(indexScope), + ); + return done; + }); + const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () { + if ( + lastSymlinkScanExpiresAt !== undefined && + (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt + ) { + symlinkScanStale = true; + } + const pending = + pendingSymlinkScan ?? + (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined); + let result = lastSymlinkScan; + if (pending && result === undefined) { + result = yield* Deferred.await(pending); + } else if (pending) { + const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT)); + if (Option.isSome(fresh)) result = fresh.value; + } + if (result === undefined) + return yield* Effect.die("The symlink scan finished without a result."); + return { + // Git's ignore rules hide a link the same way searchVisible hides the files it indexes. + entries: result.entries.filter( + (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows), + ), + linkPaths: result.linkPaths, + }; + }); + // Grows the first page until hidden entries can no longer crowd visible ones out of it. const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* ( query: string, @@ -523,6 +897,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }), ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + invalidateSymlinkScan(); }); const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( @@ -532,12 +907,15 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( "", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", - (pageSize) => finder.call("mixedSearch", "", { pageSize }), + (pageSize) => finder.call("mixedSearchAsync", "", { pageSize }), mixedItemPath, ); const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows); - const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) => - left.path.localeCompare(right.path), + const symlinks = yield* listSymlinkEntries(); + // fff's watcher can index a link the scan rejected; only accepted links are listed. + const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path)); + const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted( + (left, right) => left.path.localeCompare(right.path), ); const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES); return { @@ -554,35 +932,45 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( kind: ProjectEntryKind | undefined, imageOnly: boolean | undefined, ) { - const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); + const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries(); + const symlinks = allSymlinks.filter((entry) => + imageOnly + ? entry.kind === "file" && isProjectFaviconPath(entry.path) + : kind === undefined || entry.kind === kind, + ); + // Index results that are filtered-out links get dropped in the merge, so fetch past them. + const indexLimit = limit + linkPaths.size - symlinks.length; + const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, indexLimit + 1); + const merge = (indexed: ProjectSearchEntriesResult) => + mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit); if (kind === "file" || imageOnly) { const result = yield* searchVisible( query, pageSize, "fileSearch", - (size) => finder.call("fileSearch", query, { pageSize: size }), + (size) => finder.call("fileSearchAsync", query, { pageSize: size }), (item) => item.relativePath, ); - return mapFileSearchResult(result, limit, hostIsWindows, imageOnly); + return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly)); } if (kind === "directory") { const result = yield* searchVisible( query, pageSize, "directorySearch", - (size) => finder.call("directorySearch", query, { pageSize: size }), + (size) => finder.call("directorySearchAsync", query, { pageSize: size }), (item) => item.relativePath, ); - return mapDirectorySearchResult(result, limit, hostIsWindows); + return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows)); } const result = yield* searchVisible( query, pageSize, "mixedSearch", - (size) => finder.call("mixedSearch", query, { pageSize: size }), + (size) => finder.call("mixedSearchAsync", query, { pageSize: size }), mixedItemPath, ); - return mapMixedSearchResult(result, limit, hostIsWindows); + return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows)); }); const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( @@ -617,7 +1005,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( do { const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now())); const result = yield* runSearch(input.query, input.limit, "grep", () => - finder.call("grep", searchQuery, { + finder.call("grepAsync", searchQuery, { mode: regexMode ? "regex" : "plain", smartCase: !input.caseSensitive && !regexMode, maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize), diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index ee423c47d06ab..21b5e0e422267 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -1,6 +1,8 @@ import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -9,9 +11,10 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import { isWithinRoot } from "./KnownWorkspaces.ts"; +import { withWorkspaceLease } from "./workspaceLease.ts"; import { TerminalCwdRecovery } from "../terminal/Manager.ts"; -class WorktreeRecreateError extends Schema.TaggedError()( +export class WorktreeRecreateError extends Schema.TaggedError()( "WorktreeRecreateError", { worktreePath: Schema.String, @@ -33,6 +36,9 @@ class WorktreeRecreateNoBaseError extends Schema.TaggedError + fileSystem.exists(path.join(worktreePath, ".git")).pipe( + Effect.flatMap((hasGit) => + hasGit + ? Effect.succeed(false) + : fileSystem.readDirectory(worktreePath).pipe( + Effect.flatMap((entries) => + Effect.forEach(entries, (entry) => + LEFTOVER_WORKTREE_ENTRIES.has(entry) + ? fileSystem + .stat(path.join(worktreePath, entry)) + .pipe(Effect.map((info) => info.type === "Directory")) + : Effect.succeed(false), + ), + ), + Effect.map((leftovers) => leftovers.every(Boolean)), + ), + ), + Effect.orElseSucceed(() => false), + ); + const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* ( cwd: string, remoteName: string | null, @@ -116,7 +145,8 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { const { worktreePath, branch } = thread; if (worktreePath === null || branch === null) return; const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true)); - if (exists || !(yield* isManagedWorktreePath(worktreePath))) return; + const leftover = exists && (yield* isLeftoverFolder(worktreePath)); + if ((exists && !leftover) || !(yield* isManagedWorktreePath(worktreePath))) return; const project = yield* projects.getById(thread.projectId).pipe( Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), @@ -127,7 +157,9 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { worktreePath, branch, }); - yield* recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch }).pipe( + // `git worktree add` refuses a non-empty target. + yield* (leftover ? fileSystem.remove(worktreePath, { recursive: true }) : Effect.void).pipe( + Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), Effect.mapError((cause) => cause._tag === "WorktreeRecreateNoBaseError" ? cause @@ -137,6 +169,31 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { }); }); +export class ThreadWorktreeRestore extends Context.Service< + ThreadWorktreeRestore, + { + readonly restore: ( + thread: WorktreeThread, + ) => Effect.Effect; + } +>()("t3/workspace/restoreMissingWorktree/ThreadWorktreeRestore") {} + +// Turn start restores under the same lease, so concurrent restores see each other's worktree. +export const layerThreadWorktreeRestore = Layer.effect( + ThreadWorktreeRestore, + Effect.gen(function* () { + const path = yield* Path.Path; + const restore = yield* makeRestoreMissingWorktree; + return { + restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { + return yield* thread.worktreePath === null + ? restore(thread) + : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); + }), + }; + }), +); + // Worktree setup uses terminals, so recovery must stay outside TerminalManager. export const makePrepareTerminalLaunch = Effect.fn( "restoreMissingWorktree.makePrepareTerminalLaunch", diff --git a/apps/server/src/workspace/workspaceLease.ts b/apps/server/src/workspace/workspaceLease.ts index 8ad6e41b859c8..90e6124bb1865 100644 --- a/apps/server/src/workspace/workspaceLease.ts +++ b/apps/server/src/workspace/workspaceLease.ts @@ -1,4 +1,7 @@ +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import type * as Path from "effect/Path"; import * as Semaphore from "effect/Semaphore"; const leases = new Map(); @@ -20,3 +23,92 @@ export const withWorkspaceLease = ( ), ); }); + +// A restore rewrites files under its directory, so it must exclude provider +// startup in any overlapping workspace: symlink aliases, parents, and children. +// Kept apart from withWorkspaceLease because that lease is non-reentrant and +// restores call Git work that leases the project root. +interface Reservation { + readonly cwd: string; + readonly kind: "restore" | "turn-start"; +} + +const reservations = new Set(); +let reservationReleased = Deferred.makeUnsafe(); + +// path.relative folds win32 drive-letter case and treats a POSIX backslash as +// part of a name, unlike a raw prefix check. +const contains = (path: Path.Path, parent: string, child: string) => { + const relative = path.relative(parent, child); + return ( + relative === "" || + (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)) + ); +}; + +const conflicts = (path: Path.Path, a: Reservation, b: Reservation) => + (a.kind === "restore" || b.kind === "restore") && + (contains(path, a.cwd, b.cwd) || contains(path, b.cwd, a.cwd)); + +const reserve = (path: Path.Path, reservation: Reservation): Effect.Effect => + Effect.suspend(() => { + for (const held of reservations) { + if (conflicts(path, held, reservation)) { + return Deferred.await(reservationReleased).pipe(Effect.andThen(reserve(path, reservation))); + } + } + reservations.add(reservation); + return Effect.void; + }); + +const release = (reservation: Reservation) => + Effect.sync(() => { + if (!reservations.delete(reservation)) return; + const released = reservationReleased; + reservationReleased = Deferred.makeUnsafe(); + Deferred.doneUnsafe(released, Effect.void); + }); + +// A worktree removed by storage cleanup is recreated inside the reserved +// section, so resolve its nearest existing ancestor: a symlink alias above it +// must still canonicalize the same on both sides. Walks at most the path depth. +const canonicalize = ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + target: string, +): Effect.Effect => + fileSystem.realPath(target).pipe( + Effect.catchReason("PlatformError", "NotFound", () => { + const parent = path.dirname(target); + return parent === target + ? Effect.succeed(target) + : canonicalize(fileSystem, path, parent).pipe( + Effect.map((resolved) => path.join(resolved, path.basename(target))), + ); + }), + Effect.orElseSucceed(() => target), + ); + +const withReservation = + (kind: Reservation["kind"]) => + ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + cwd: string, + effect: Effect.Effect, + ): Effect.Effect => + canonicalize(fileSystem, path, cwd).pipe( + Effect.flatMap((canonical) => { + const reservation: Reservation = { cwd: canonical, kind }; + return reserve(path, reservation).pipe( + Effect.andThen(effect), + Effect.ensuring(release(reservation)), + ); + }), + ); + +/** Exclusive over every overlapping workspace while checkpoint files are restored. */ +export const withCheckpointRestoreReservation = withReservation("restore"); + +/** Waits out overlapping restores; turn startups never wait on each other. */ +export const withTurnStartReservation = withReservation("turn-start"); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c36b935741e7d..c4470e0905c8a 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -237,7 +237,7 @@ it.effect("resends a reveal kind and remote targets that outlast the snapshot ti assert.deepEqual(remote.config.remoteOpenTargets, targets); assert.equal(remote.config.shellRevealInFileManagerKind, "file-explorer"); } - }).pipe(Effect.scoped), + }), ); it.effect("runs editor, remote open target and direct endpoint discovery side by side", () => @@ -276,25 +276,23 @@ const ReplayTestLayer = OrchestrationEventStore.layer.pipe( Layer.provideMerge(SqlitePersistence.layerMemory), ); -it.live.each(["thread", "shell"] as const)( - "%s resume skips unknown types, synchronizes, and receives the live tail", - (scope) => - Effect.gen(function* () { - const store = yield* OrchestrationEventStore.OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-05T00:00:00.000Z"; - const threadId = ThreadId.make("thread:replay"); - const projectId = ProjectId.make("project:replay"); - const project = { - id: projectId, - title: "Replay", - workspaceRoot: "/tmp/replay", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - } satisfies OrchestrationProjectShell; - const insert = (version: number, unknown = false) => sql<{ sequence: number }>` +const resumeSkipsUnknownTypes = (scope: "thread" | "shell") => + Effect.gen(function* () { + const store = yield* OrchestrationEventStore.OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = "2026-01-05T00:00:00.000Z"; + const threadId = ThreadId.make("thread:replay"); + const projectId = ProjectId.make("project:replay"); + const project = { + id: projectId, + title: "Replay", + workspaceRoot: "/tmp/replay", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + const insert = (version: number, unknown = false) => sql<{ sequence: number }>` INSERT INTO orchestration_events ( event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version @@ -309,85 +307,91 @@ it.live.each(["thread", "shell"] as const)( )}, '{}', 2 ) RETURNING sequence `; - const [before] = yield* insert(0); - yield* insert(1, true); - const [after] = yield* insert(2); - const [highWater] = yield* insert(3, true); - const updates = yield* PubSub.unbounded(); - let liveSequence = 0; - const consume = ( - stream: Stream.Stream, - ) => - stream.pipe( - Stream.tap((item) => - Effect.gen(function* () { - if (item.kind !== "synchronized") return; - const [live] = yield* insert(4); - liveSequence = live!.sequence; - const events = yield* store - .readApplicationEvents({ - afterSequence: highWater!.sequence, - throughSequence: liveSequence, - }) - .pipe(Stream.runCollect); - yield* store.publishCommitted(events); - }), - ), - Stream.takeUntil((item) => item.sequence === liveSequence), - Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })), - Stream.runCollect, - ); - const subscription = Effect.gen(function* () { - return scope === "thread" - ? yield* subscribeOrchestrationV2Thread({ - threadId, - afterSequence: before!.sequence, - requestCompletionMarker: true, - }).pipe(Effect.flatMap(consume)) - : yield* subscribeOrchestrationV2Shell({ - afterSequence: before!.sequence, - requestCompletionMarker: true, - }).pipe(Effect.flatMap(consume)); - }); - const items = yield* subscription.pipe( - Effect.provideService(ThreadManagement.ThreadManagementService, { - ensureLegacyTranscript: () => Effect.void, - getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"), - listActiveSubagentThreadIds: () => Effect.succeed([]), - streamStoredEventsFrom: ( - input: Parameters< - ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"] - >[0], - ) => { - assert.equal(input?.afterSequence, highWater!.sequence); - return store - .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 }) - .pipe( - Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event), - ); - }, - } as unknown as ThreadManagement.ThreadManagementService["Service"]), - Effect.provideService(ProjectStore.ProjectStoreV2, { - listShells: () => Effect.succeed([]), - } as unknown as ProjectStore.ProjectStoreV2["Service"]), - Effect.provideService(ProjectService.ProjectService, { - getShell: () => Effect.succeedSome(project), - } as unknown as ProjectService.ProjectService["Service"]), - Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { - subscribeChanges: PubSub.subscribe(updates), - } as ProjectEnrichment.ProjectEnrichmentService["Service"]), - ); - assert.deepEqual( - items.map((item) => item.kind), - scope === "thread" - ? ["event", "synchronized", "event"] - : ["project.updated", "synchronized", "project.updated"], - ); - assert.deepEqual( - items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])), - [after!.sequence, liveSequence], + const [before] = yield* insert(0); + yield* insert(1, true); + const [after] = yield* insert(2); + const [highWater] = yield* insert(3, true); + const updates = yield* PubSub.unbounded(); + let liveSequence = 0; + const consume = ( + stream: Stream.Stream, + ) => + stream.pipe( + Stream.tap((item) => + Effect.gen(function* () { + if (item.kind !== "synchronized") return; + const [live] = yield* insert(4); + liveSequence = live!.sequence; + const events = yield* store + .readApplicationEvents({ + afterSequence: highWater!.sequence, + throughSequence: liveSequence, + }) + .pipe(Stream.runCollect); + yield* store.publishCommitted(events); + }), + ), + Stream.takeUntil((item) => item.sequence === liveSequence), + Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })), + Stream.runCollect, ); - }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), + const subscription = Effect.gen(function* () { + return scope === "thread" + ? yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: before!.sequence, + requestCompletionMarker: true, + }).pipe(Effect.flatMap(consume)) + : yield* subscribeOrchestrationV2Shell({ + afterSequence: before!.sequence, + requestCompletionMarker: true, + }).pipe(Effect.flatMap(consume)); + }); + const items = yield* subscription.pipe( + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"), + listActiveSubagentThreadIds: () => Effect.succeed([]), + streamStoredEventsFrom: ( + input: Parameters< + ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"] + >[0], + ) => { + assert.equal(input?.afterSequence, highWater!.sequence); + return store + .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 }) + .pipe(Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event)); + }, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + listShells: () => Effect.succeed([]), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService(ProjectService.ProjectService, { + getShell: () => Effect.succeedSome(project), + } as unknown as ProjectService.ProjectService["Service"]), + Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { + subscribeChanges: PubSub.subscribe(updates), + } as ProjectEnrichment.ProjectEnrichmentService["Service"]), + ); + assert.deepEqual( + items.map((item) => item.kind), + scope === "thread" + ? ["event", "synchronized", "event"] + : ["project.updated", "synchronized", "project.updated"], + ); + assert.deepEqual( + items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])), + [after!.sequence, liveSequence], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)); + +it.effect("thread resume skips unknown types, synchronizes, and receives the live tail", () => + resumeSkipsUnknownTypes("thread"), +); + +// Shell updates batch through `Stream.groupedWithin`, whose window needs real time to close. +it.live("shell resume skips unknown types, synchronizes, and receives the live tail", () => + resumeSkipsUnknownTypes("shell"), ); it.effect("coalesces streaming replay before synchronization and the live tail", () => @@ -1140,7 +1144,6 @@ it.effect.each([ Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1252,7 +1255,6 @@ it.effect("access changes made while the snapshot loads reach the client after i Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1607,7 +1609,6 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1779,7 +1780,6 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1853,7 +1853,6 @@ it.effect("a git action that fails partway still refreshes the repository status Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -1941,7 +1940,6 @@ it.effect("a publish whose push fails still refreshes the new remote", () => Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); @@ -2445,6 +2443,5 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Layer.mock(ServerBrowser.ServerBrowser)({}), ), ), - Effect.scoped, ), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 67671d307d87b..f655020a3a5e6 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2824,6 +2824,8 @@ export const layerWsRpc = ( ), ), [WS_METHODS.pullRequestsSubscribeRefreshes]: () => pullRequests.subscribeRefreshes, + [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () => + pullRequests.subscribeLinkedThreadRefreshes, [WS_METHODS.pullRequestsReviewerCandidates]: (input) => withPullRequestViewer(input, pullRequests.reviewerCandidates(input)), [WS_METHODS.pullRequestsRequestReviewers]: (input) => @@ -3172,7 +3174,15 @@ export const layerWsRpc = ( [WS_METHODS.vcsCreateWorktree]: (input) => gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsRemoveWorktree]: (input) => - gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + gitWorkflow.removeWorktree(input).pipe( + Effect.tap(() => refreshGitStatus(input.cwd)), + // Subscribers of the removed checkout learn it is no longer a repository. + Effect.tap(() => + vcsStatusBroadcaster + .refreshLocalStatus(input.path) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), + ), + ), [WS_METHODS.vcsCreateRef]: (input) => gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsSwitchRef]: (input) => diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 44de1196b2b7c..28edc42d406a8 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -184,16 +184,24 @@ export function HostedBrowserWebview(props: { if (!disposed) remountCrashedWebview(); }, recovery.delayMs); }; - // Guest clicks only emit focus here; replay pointerdown to dismiss host popups. + // Guest clicks never reach this document, so replay a pointerdown to dismiss host popups. + // The guest preload reports each press, since the guest does not always take focus. const dismissHostPopups = () => { webview.dispatchEvent( new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }), ); }; + const guestPointerDown = (event: Event) => { + // Mirrors POINTER_DOWN_HOST_CHANNEL in apps/desktop/src/preview/GuestProtocol.ts. + if ((event as Event & { channel?: string }).channel === "preview:pointer-down") { + dismissHostPopups(); + } + }; webview.addEventListener("did-attach", register); webview.addEventListener("dom-ready", register); webview.addEventListener("render-process-gone", recoverGuest); webview.addEventListener("focus", dismissHostPopups); + webview.addEventListener("ipc-message", guestPointerDown); register(); return () => { disposed = true; @@ -202,6 +210,7 @@ export function HostedBrowserWebview(props: { webview.removeEventListener("dom-ready", register); webview.removeEventListener("render-process-gone", recoverGuest); webview.removeEventListener("focus", dismissHostPopups); + webview.removeEventListener("ipc-message", guestPointerDown); }; }, [ clientSettingsHydrated, diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx index e32e8f76f1a9d..a881650f69bcf 100644 --- a/apps/web/src/browser/ServerBrowserSurface.tsx +++ b/apps/web/src/browser/ServerBrowserSurface.tsx @@ -46,6 +46,7 @@ export interface ServerBrowserHandle { readonly navigate: (url: string) => void; readonly history: (delta: -1 | 1) => void; readonly reload: (options?: { readonly ignoreCache?: boolean }) => void; + readonly stopLoading: () => void; readonly viewport: (setting: PreviewViewportSetting) => void; readonly canvas: () => HTMLCanvasElement | null; } @@ -311,6 +312,7 @@ export function ServerBrowserSurface(props: { history: (delta) => send({ type: "history", delta }), reload: (options) => send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }), + stopLoading: () => send({ type: "stopLoading" }), viewport: (setting) => send({ type: "viewport", setting }), canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null), }), diff --git a/apps/web/src/browser/browserDefaults.ts b/apps/web/src/browser/browserDefaults.ts index bf1c2da40db87..5cc74bb1b7f0d 100644 --- a/apps/web/src/browser/browserDefaults.ts +++ b/apps/web/src/browser/browserDefaults.ts @@ -5,6 +5,7 @@ import { type DesktopPreviewTabDefaults, type PreviewAppearancePreference, type PreviewViewportSetting, + type PreviewZoomFactor, } from "@t3tools/contracts"; import { @@ -17,7 +18,7 @@ import { resolveResponsiveBrowserViewportSize } from "./browserViewportLayout"; export interface BrowserDefaults { readonly viewport: PreviewViewportSetting; - readonly zoomFactor: number; + readonly zoomFactor: PreviewZoomFactor; readonly appearance: PreviewAppearancePreference; readonly autoShowFloatingPreview: boolean; readonly profiles: ReadonlyArray; @@ -26,7 +27,7 @@ export interface BrowserDefaults { const toBrowserDefaults = (settings: { readonly browserDefaultViewport: PreviewViewportSetting; - readonly browserDefaultZoomFactor: number; + readonly browserDefaultZoomFactor: PreviewZoomFactor; readonly browserDefaultAppearance: PreviewAppearancePreference; readonly browserAutoShowFloatingPreview: boolean; readonly browserProfiles: ReadonlyArray; diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.ts index a997ee2b552e4..db1a58e98dfb9 100644 --- a/apps/web/src/browser/openFileInPreview.ts +++ b/apps/web/src/browser/openFileInPreview.ts @@ -85,7 +85,9 @@ export async function openUrlInPreview(input: { url: input.url, viewport: defaults.viewport, profileId: input.profileId ?? defaults.profileId, - ...(runtime === undefined ? {} : { runtime }), + ...(runtime === undefined + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); return mapAtomCommandResult(result, (snapshot) => { diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 3d9c064cfcb23..3bb70c8b609eb 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -26,6 +26,7 @@ import { useAddProjectTargets } from "../hooks/useAddProjectTargets"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; import { + COPIED_FILES_MAX_COUNT, COPYABLE_FILE_MAX_BYTES, addProjectToMachine, isDefaultCopiedFile, @@ -35,6 +36,7 @@ import { newProjectId } from "../lib/utils"; import { readProject, subscribeProject, useProject } from "../state/entities"; import { useEnvironments } from "../state/environments"; import { projectEnvironment } from "../state/projects"; +import { useDebouncedValue } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { Button } from "./ui/button"; @@ -121,8 +123,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [pathOverride, setPathOverride] = useState(null); const destinationPath = pathOverride ?? defaultPath; - const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true; - const ignoredFiles = useEnvironmentQuery( + const capabilities = source?.serverConfig?.environment.capabilities; + const canListFiles = capabilities?.ignoredFileListing === true; + const canSearchFiles = canListFiles && capabilities?.ignoredFileSearch === true; + const allIgnoredFiles = useEnvironmentQuery( project && canListFiles ? projectEnvironment.listIgnoredFiles({ environmentId: project.environmentId, @@ -130,13 +134,29 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe }) : null, ); + const [fileQuery, setFileQuery] = useState(""); + const sentFileQuery = useDebouncedValue(fileQuery.trim(), 120); + const searching = canSearchFiles && sentFileQuery.length > 0; + const searchedFiles = useEnvironmentQuery( + project && searching + ? projectEnvironment.listIgnoredFiles({ + environmentId: project.environmentId, + input: { cwd: project.workspaceRoot, query: sentFileQuery }, + }) + : null, + ); + const ignoredFiles = searching ? searchedFiles : allIgnoredFiles; const files = ignoredFiles.data?.files ?? []; - const [selected, setSelected] = useState | null>(null); - const selectedFiles = selected ?? defaultSelection(files); + // Keyed by path with the file kept, so picks made under one search survive the next. + const [selected, setSelected] = useState | null>(null); + const selectedFiles = selected ?? defaultSelection(allIgnoredFiles.data?.files ?? []); const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES); - const selectedBytes = files - .filter((file) => selectedFiles.has(file.path)) - .reduce((total, file) => total + file.byteLength, 0); + const allCopyableSelected = copyable.every((file) => selectedFiles.has(file.path)); + const atSelectionLimit = selectedFiles.size >= COPIED_FILES_MAX_COUNT; + const selectedBytes = [...selectedFiles.values()].reduce( + (total, file) => total + file.byteLength, + 0, + ); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); @@ -146,11 +166,19 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const unavailable = project === null || target === null || - (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null); - const toggleFile = (path: string, checked: boolean) => { - const next = new Set(selectedFiles); - if (checked) next.add(path); - else next.delete(path); + (canListFiles && allIgnoredFiles.data === null && allIgnoredFiles.error === null); + const toggleFile = (file: ProjectIgnoredFile, checked: boolean) => { + const next = new Map(selectedFiles); + if (!checked) next.delete(file.path); + else if (!atSelectionLimit) next.set(file.path, file); + setSelected(next); + }; + const toggleShownFiles = () => { + const next = new Map(selectedFiles); + for (const file of copyable) { + if (allCopyableSelected) next.delete(file.path); + else if (next.size < COPIED_FILES_MAX_COUNT) next.set(file.path, file); + } setSelected(next); }; @@ -198,7 +226,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe title: project.title, remoteUrl, destinationPath: destinationPath.trim(), - files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path), + files: [...selectedFiles.keys()], }); close(); openClonedProject(scopeProjectRef(target.environmentId, projectId)); @@ -334,33 +362,41 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {copyable.length > 0 ? ( <> - {selectedFiles.size} of {files.length} + {selectedFiles.size} of {allIgnoredFiles.data?.files.length ?? 0} {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""} - ) : null} + {canSearchFiles && (allIgnoredFiles.data?.truncated || fileQuery.length > 0) ? ( + setFileQuery(event.target.value)} + // Enter would otherwise submit the clone. + onKeyDown={(event) => { + if (event.key === "Enter") event.preventDefault(); + }} + spellCheck={false} + autoComplete="off" + /> + ) : null} {ignoredFiles.error ? (

{ignoredFiles.error}

) : files.length === 0 ? (

- {ignoredFiles.isSuccess - ? "No ignored files to copy." - : "Finding ignored files…"} + {!ignoredFiles.isSuccess + ? "Finding ignored files…" + : searching + ? "No ignored files match." + : "No ignored files to copy."}

) : (
@@ -369,7 +405,8 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe key={file.path} file={file} checked={selectedFiles.has(file.path)} - onCheckedChange={(checked) => toggleFile(file.path, checked)} + disabled={atSelectionLimit && !selectedFiles.has(file.path)} + onCheckedChange={(checked) => toggleFile(file, checked)} /> ))}
@@ -377,6 +414,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {ignoredFiles.data?.truncated ? (

Showing the first {files.length} files. + {canSearchFiles ? " Search to find the rest." : ""}

) : null}

@@ -415,29 +453,37 @@ function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: : ""; } -function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet { - return new Set( +function defaultSelection( + files: readonly ProjectIgnoredFile[], +): ReadonlyMap { + return new Map( files .filter( (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path), ) - .map((file) => file.path), + .map((file) => [file.path, file]), ); } function IgnoredFileRow({ file, checked, + disabled, onCheckedChange, }: { file: ProjectIgnoredFile; checked: boolean; + disabled: boolean; onCheckedChange: (checked: boolean) => void; }) { const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES; return (

{children}
; } return (

diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 3437683f9ce98..0746f55728a9f 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -24,7 +24,7 @@ import { threadWithHistory, type FakeDriver, } from "../../test/fakeEnvironment"; -import { act, render } from "../../test/render"; +import { act, fakeTimers, render } from "../../test/render"; // The socket is the only fake layer; see test/appScenarios.renders.tsx. vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { @@ -260,3 +260,48 @@ it("Enter on an empty prompt resumes an interrupted thread", async () => { ), ); }); + +it("opening a thread or returning to the window on a touch tablet does not focus the composer", async () => { + const realMatchMedia = window.matchMedia.bind(window); + using _touch = vi + .spyOn(window, "matchMedia") + .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query)); + const first = threadWithHistory("thread-29469-a", 1); + const second = threadWithHistory("thread-29469-b", 1); + using _environment = installFakeEnvironment([first, second]); + // iPad Pro 11 in landscape: the desktop layout, above max-sm. + await page.viewport(1194, 834); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${first.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const composer = page.getByTestId("composer-editor"); + await expect.element(page.getByText(`Answer 0 for ${first.id}.`)).toBeVisible(); + + // Fake frames hold the next thread entry's focus frame until the test advances it. + using _timers = fakeTimers(); + await act(() => + router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: ENVIRONMENT_ID, threadId: second.id }, + }), + ); + await expect.element(page.getByText(`Answer 0 for ${second.id}.`)).toBeVisible(); + vi.advanceTimersToNextFrame(); + // Focusing the editor raises the on-screen keyboard, which shrinks the page on iPadOS. + expect(document.activeElement).not.toBe(composer.element()); + + // ChatView waits two frames after window focus before refocusing the composer. + window.dispatchEvent(new FocusEvent("focus")); + vi.advanceTimersToNextFrame(); + vi.advanceTimersToNextFrame(); + expect(document.activeElement).not.toBe(composer.element()); +}); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 8223e03540405..8aa4df4c09ba5 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -9,7 +9,11 @@ import { deriveAvailableRevertTurnCounts, deriveThreadPendingBackgroundTasks, } from "./ChatView.logic"; -import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; +import { + isThreadEnvironmentLocked, + recallCheckoutIsRepo, + rememberCheckoutIsRepo, +} from "./ChatView.logic"; import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; import { deriveProviderInstanceEntries } from "../providerInstances"; import { ensureInlineContextReferences } from "../lib/composerContextReferences"; @@ -133,6 +137,26 @@ describe("deriveComposerSendState", () => { }); }); +describe("isThreadEnvironmentLocked", () => { + it.each([ + { name: "an empty unbound thread", providerThread: null, expected: false }, + { + name: "an imported session bound before its first run", + providerThread: "imported", + expected: true, + }, + ])("locks $name: $expected", ({ providerThread, expected }) => { + expect( + isThreadEnvironmentLocked({ + messageCount: 0, + hasRuntime: false, + activeProviderThreadId: + providerThread === null ? null : ProviderThreadId.make(providerThread), + }), + ).toBe(expected); + }); +}); + describe("buildExpiredTerminalContextToastCopy", () => { it("refers to several expired contexts as them", () => { expect(buildExpiredTerminalContextToastCopy(2, "empty")).toEqual({ diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 0848d27c05bdb..94fc6a8cad279 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -32,6 +32,7 @@ import { type PreviewAnnotationPayload, ProviderDriverKind, type ProviderInstanceId, + type ProviderThreadId, type ServerProvider, type ScopedProjectRef, type ScopedThreadRef, @@ -1070,9 +1071,9 @@ export function hasServerAcknowledgedLocalDispatch(input: { } // Window return puts the caret in the composer unless focus is deliberate: another text field, -// a terminal, an open dialog, menu, or popup, a region or sidebar row reached from the keyboard, -// or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked row -// yields to the composer. +// a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached from the +// keyboard, or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked +// row yields to the composer. export function shouldRefocusComposerOnWindowFocus( activeElement: | (Pick & { isContentEditable?: boolean }) @@ -1541,3 +1542,12 @@ export function deriveAvailableRevertTurnCounts(projection: ThreadStructure | nu } return available; } + +/** An imported native session is bound before it has messages or runs, and its cwd is fixed. */ +export function isThreadEnvironmentLocked(input: { + readonly messageCount: number; + readonly hasRuntime: boolean; + readonly activeProviderThreadId: ProviderThreadId | null; +}): boolean { + return input.messageCount > 0 || input.hasRuntime || input.activeProviderThreadId !== null; +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 583e4e0e8790b..3e366c93a2bc3 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -38,7 +38,7 @@ import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider"; import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner"; -import { resolveDraftHeroState } from "./ChatView.logic"; +import { isThreadEnvironmentLocked, resolveDraftHeroState } from "./ChatView.logic"; import { useQueuedRunEdit } from "./chat/useQueuedRunEdit"; import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; @@ -427,6 +427,8 @@ type ChatViewProps = const DismissedFallbackWindowSchema = Schema.NullOr(Schema.String); +const ignoreComposerFocus = () => {}; + export default function ChatView(props: ChatViewProps) { const { environmentId, @@ -714,6 +716,8 @@ export default function ChatView(props: ChatViewProps) { }, [isWorkspaceFileDragActive]); const prefersPlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY); const isMobileViewport = useMediaQuery("max-sm"); + // Focusing the composer without a tap raises the on-screen keyboard on touch devices. + const isCoarsePointer = useMediaQuery({ pointer: "coarse" }); const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState(null); const threadPanelPopoverAnchorRef = useRef(null); const [terminalUiLaunchContext, setTerminalUiLaunchContext] = @@ -1285,7 +1289,13 @@ export default function ChatView(props: ChatViewProps) { advertisedFileAttachmentBytes === null ? null : clampFileAttachmentUploadBytes(advertisedFileAttachmentBytes); - const envLocked = Boolean(activeThread && (activeMessageCount > 0 || activeRuntime !== null)); + const envLocked = + Boolean(activeThread) && + isThreadEnvironmentLocked({ + messageCount: activeMessageCount, + hasRuntime: activeRuntime !== null, + activeProviderThreadId: serverThread?.activeProviderThreadId ?? null, + }); // onEnvironmentChange only retargets an unsent draft. envLocked alone does not // rule out a started thread: one whose machine is offline never loads its // messages, so it would otherwise be offered a machine picker that does nothing. @@ -2136,12 +2146,20 @@ export default function ChatView(props: ChatViewProps) { workspaceLayoutElement, !embedded, terminalUiState.terminalOpen, - focusComposerStable, + isCoarsePointer ? ignoreComposerFocus : focusComposerStable, ); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus on a fine pointer useEffect(() => { - if (embedded || !activeThread?.id || terminalUiState.terminalOpen || isMobileViewport) return; + if ( + embedded || + !activeThread?.id || + terminalUiState.terminalOpen || + isMobileViewport || + isCoarsePointer + ) { + return; + } let frame: number | null = null; const onWindowFocus = () => { if (frame !== null) window.cancelAnimationFrame(frame); @@ -2168,6 +2186,7 @@ export default function ChatView(props: ChatViewProps) { activeThread?.id, embedded, focusComposerStable, + isCoarsePointer, isMobileViewport, terminalUiState.terminalOpen, ]); diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx index 5a2682df6f656..e1f69d72e3b41 100644 --- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx @@ -8,9 +8,32 @@ import { CommandPalette } from "./CommandPalette"; import { openCommandPalette } from "../commandPaletteBus"; import { primaryServerKeybindingsAtom } from "../state/server"; -const scopes = vi.hoisted(() => ({ denied: undefined as string | undefined })); -const setup = (deniedScope?: string) => { +const scopes = vi.hoisted(() => ({ + denied: undefined as string | undefined, + sourceControl: undefined as unknown, +})); +const setup = (deniedScope?: string, sourceControl?: unknown) => { scopes.denied = deniedScope; + scopes.sourceControl = sourceControl; +}; +const githubAvailable = { + versionControlSystems: [], + sourceControlProviders: [ + { + kind: "github", + label: "GitHub", + status: "available", + version: { _tag: "None" }, + installHint: "Install GitHub CLI", + detail: { _tag: "None" }, + auth: { + status: "authenticated", + account: { _tag: "Some", value: "demo" }, + host: { _tag: "None" }, + detail: { _tag: "None" }, + }, + }, + ], }; vi.mock("@effect/atom-react", async (original) => ({ @@ -101,7 +124,7 @@ vi.mock("../state/filesystem", async (original) => ({ })); vi.mock("../state/query", async (original) => ({ ...(await original()), - useEnvironmentQuery: () => ({ data: undefined, isLoading: false }), + useEnvironmentQuery: () => ({ data: scopes.sourceControl, isLoading: false }), })); vi.mock("./settings/useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [], @@ -208,3 +231,15 @@ it.each([ await userEvent.keyboard("{Tab}"); await expect.element(submit).toHaveFocus(); }); + +it("tells screen readers whether a new project will be published", async () => { + setup(undefined, githubAvailable); + await using _screen = await render({null}); + await act(() => openCommandPalette({ open: "add-project" })); + await page.getByText("New project", { exact: true }).click(); + await page.getByRole("combobox").fill("demo-project"); + const option = page.getByRole("option", { name: /Create private repository/ }); + await expect.element(option).toHaveAttribute("aria-checked", "false"); + await option.click(); + await expect.element(option).toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index db7ea4895b7ce..895995c03e487 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -213,6 +213,8 @@ export interface CommandPaletteActionItem extends CommandPaletteItem { readonly run: () => Promise; /** A pin toggle on the row, also reached with the pin shortcut while the row is highlighted. */ readonly pin?: CommandPaletteItemPin; + /** Set on toggle rows; exposed to assistive technology as `aria-checked`. */ + readonly checked?: boolean; } export interface CommandPaletteItemPin { diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 99c87a939dd84..fe21bd2e3a635 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2427,6 +2427,7 @@ function OpenCommandPaletteDialog(props: { ), ...(isCreatingNewProject ? { disabled: true } : {}), keepOpen: true, + checked: newProjectPublishes, run: async () => { setNewProjectPublishes((publishes) => !publishes); }, diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index 864c190b89c54..8c52ad294fb42 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -250,6 +250,9 @@ function CommandPaletteResultRow(props: { {...(props.index === undefined ? {} : { index: props.index })} value={props.item.value} active={props.isActive} + {...(props.item.kind === "action" && props.item.checked !== undefined + ? { "aria-checked": props.item.checked } + : {})} onPointerDown={(event) => { if (props.item.threadRef) { startPaletteThreadDrag( diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index bc2ea348b4d2a..a614f4823f289 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -26,6 +26,22 @@ import { type ComposerPromptEditorProps, } from "./ComposerPromptEditorTiptap"; +vi.mock(import("../state/server"), async (original) => { + const { Atom } = await import("effect/reactivity"); + const { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } = + await import("@t3tools/shared/keybindings"); + return { + ...(await original()), + primaryServerKeybindingsAtom: Atom.make( + compileResolvedKeybindingsConfig([ + ...DEFAULT_KEYBINDINGS, + { key: "mod+arrowup", command: "thread.previous" }, + { key: "mod+arrowdown", command: "thread.next" }, + ]), + ), + }; +}); + const babysit: ServerProviderSkill = { name: "babysit", path: "/skills/babysit/SKILL.md", @@ -271,6 +287,29 @@ it.each([ }, ); +// The mocked server keybindings bind Command-Up and Command-Down to thread navigation. +it("leaves Command-arrow thread navigation bindings to the app on macOS", async () => { + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await mountEditor("first\nsecond"); + const { editor } = screen; + await act(async () => { + editor.commands.focus("end"); + }); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + const reachedApp: string[] = []; + const onWindowKeyDown = (event: KeyboardEvent) => { + if (!event.defaultPrevented && event.key.startsWith("Arrow")) reachedApp.push(event.key); + }; + window.addEventListener("keydown", onWindowKeyDown); + using _listener = { + [Symbol.dispose]: () => window.removeEventListener("keydown", onWindowKeyDown), + }; + + await userEvent.keyboard("{Meta>}{ArrowUp}{ArrowDown}{/Meta}"); + + expect(reachedApp).toEqual(["ArrowUp", "ArrowDown"]); +}); + it.each([ ["e", false, false], ["i", false, false], @@ -560,6 +599,31 @@ describe("Markdown markers around styled text", () => { expected: "**bo**\n**ld** after", marks: { bold: ["bo", "ld"] }, }, + { + name: "a line break after typed inline code leaves the next line plain", + value: "", + caret: 1, + keys: "`Test`{Shift>}{Enter}{/Shift}f", + expected: "`Test`\nf", + marks: { code: ["Test"] }, + }, + { + name: "a line break after typed bold leaves the next line plain", + value: "", + caret: 1, + keys: "**Test**{Shift>}{Enter}{/Shift}f", + expected: "**Test**\nf", + marks: { bold: ["Test"] }, + }, + { + name: "bold turned on after typed bold carries across a line break", + value: "", + caret: 1, + keys: `**Test**${isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}"}{Shift>}{Enter}{/Shift}f`, + expected: "**Test**\n**f**", + // The caret beside f shows it as source. + marks: { bold: ["Test"] }, + }, { name: "splitting a list item inside bold keeps both halves bold", value: "- **bold** after", diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index a974c9308844f..5a036e34611ed 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -114,6 +114,9 @@ import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { isRichTextFormattingShortcut } from "~/keybindings"; import { cn, isMacPlatform } from "~/lib/utils"; +import { isThreadNavigationShortcut } from "~/keybindings"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { primaryServerKeybindingsAtom } from "~/state/server"; import { hasCommandForKeyDown } from "~/shortcuts/dispatcher"; import { basenameOfPath } from "~/pierre-icons"; import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; @@ -1143,6 +1146,13 @@ function ComposerPromptEditorTiptapInner( !event.ctrlKey && !event.isComposing ) { + if ( + isThreadNavigationShortcut(event, appAtomRegistry.get(primaryServerKeybindingsAtom), { + context: { editableFocus: true }, + }) + ) { + return false; + } const selection = window.getSelection(); if ( selection?.anchorNode && diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 5f789469af763..51ba65933dff7 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -4,6 +4,7 @@ import { DEFAULT_CLIENT_SETTINGS, EnvironmentId, ProjectId, + RunId, ThreadId, type ClientSettings, type ReviewBranchCommitsResult, @@ -35,6 +36,8 @@ const state = vi.hoisted(() => ({ localRefs: null as unknown as ResultAtom, remoteRefs: null as unknown as ResultAtom, commits: null as unknown as ResultAtom, + checkpoints: [] as unknown[], + checkpointDiff: null as { diff: string } | null, })); vi.mock("~/state/server", () => ({ @@ -59,7 +62,7 @@ vi.mock("~/state/vcs", () => ({ vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => state.thread, useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }), - useThreadCheckpointSummaries: () => [], + useThreadCheckpointSummaries: () => state.checkpoints, useQuietThreadVisibleTurnItems: () => [], })); vi.mock("~/state/filesystem", () => ({ @@ -77,7 +80,7 @@ vi.mock("~/hooks/useTheme", () => ({ subscribeRenderedAppearance: () => () => {}, })); vi.mock("~/state/queries", () => ({ - useCheckpointDiff: () => ({ data: null, error: null, isPending: false }), + useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }), useTurnItemDetail: () => ({ data: null, error: null, isPending: false }), useDebouncedValue: (value: A) => value, })); @@ -126,6 +129,8 @@ function setup(failedBaseRef: string | null) { }; reset(); state.diffFilesCollapsed = false; + state.checkpoints = []; + state.checkpointDiff = null; const patch = Atom.make>( AsyncResult.initial(), ); @@ -267,3 +272,33 @@ it.each([false, true])( await expect.element(toggle).toHaveAttribute("aria-expanded", "false"); }, ); + +it("says a turn diff cut off at the server's size limit is incomplete", async () => { + using context = setup("origin/orphan"); + state.checkpoints = [ + { + runId: "run", + checkpointTurnCount: 1, + checkpointRef: "ref", + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00Z", + }, + ]; + state.checkpointDiff = { + diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]", + }; + useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); + await using screen = await render( + +

+ +
+ , + ); + await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible(); + await expect + .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete.")) + .toBeVisible(); +}); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 4231b669aa76b..2b0a6a78d4ec2 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -6,7 +6,12 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; -import type { ReviewBranchCommitsResult, ScopedThreadRef, RunId } from "@t3tools/contracts"; +import { + CHECKPOINT_DIFF_TRUNCATED_MARKER, + type ReviewBranchCommitsResult, + type ScopedThreadRef, + type RunId, +} from "@t3tools/contracts"; import { ArrowRightIcon, CheckIcon, @@ -232,7 +237,8 @@ export default function DiffPanel({ wordWrap: settings.wordWrap, })); const diffLayout = settings.diffLayout; - const [wordWrap, setWordWrap] = useState(settings.wordWrap); + const [wordWrapOverride, setWordWrapOverride] = useState(null); + const wordWrap = wordWrapOverride ?? settings.wordWrap; const diffIgnoreWhitespace = useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? settings.diffIgnoreWhitespace; const [fileTreeOpen, setFileTreeOpen] = useLocalStorage( @@ -482,7 +488,10 @@ export default function DiffPanel({ : gitDiff; const isSelectedPatchTruncated = toolCallPreview?.truncated === true || - (isGitSelection && selectedGitSource?.truncated === true); + (isGitSelection && selectedGitSource?.truncated === true) || + (!toolCallSelection && + selectedTurn !== undefined && + selectedPatch?.endsWith(CHECKPOINT_DIFF_TRUNCATED_MARKER) === true); const selectedPatchQuery = toolCallSelection ? toolCallDetail : selectedTurn @@ -1218,7 +1227,7 @@ export default function DiffPanel({ size="sm" pressed={wordWrap} onPressedChange={(pressed) => { - setWordWrap(Boolean(pressed)); + setWordWrapOverride(Boolean(pressed)); }} /> } diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index 10bf817b7363f..d2a15729b0df2 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -71,4 +71,36 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).not.toHaveBeenCalled(); }); + + // A vertical scroll 15° off vertical. + const drift = Array.from({ length: 30 }, () => [-4, 15] as const); + it.each([ + [ + "a vertical scroll that starts slightly diagonally keeps the thread", + [[-5, 3], ...drift], + false, + ], + [ + "a swipe that leans diagonally for two events navigates", + [ + [-5, 3], + [-2, 2], + [-150, 0], + ], + true, + ], + ["a single diagonal event past the trigger keeps the thread", [[-130, 100]], false], + ] as const)("%s", async (_name, events, navigates) => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await render(); + const panel = screen.container.appendChild(document.createElement("div")); + for (const [deltaX, deltaY] of [...events, [0, 0] as const]) { + panel.dispatchEvent( + new WheelEvent("wheel", { deltaX, deltaY, bubbles: true, composed: true }), + ); + } + + expect(navigateHistory).toHaveBeenCalledTimes(navigates ? 1 : 0); + }); }); diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index e1adc04491a91..2924f82cd3136 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -7,6 +7,10 @@ import { canNavigateHistory, navigateHistory, type HistoryDirection } from "../n const SWIPE_TRIGGER_DISTANCE = 120; // Movement needed before the gesture picks an axis; first events are often diagonal. const SWIPE_AXIS_LOCK_DISTANCE = 8; +// Vertical scrolls drift sideways, so a swipe's horizontal travel must clearly dominate once +// it has moved far enough for its direction to be more than noise. +const SWIPE_HORIZONTAL_DOMINANCE = 2; +const SWIPE_DOMINANCE_DISTANCE = 30; const MOMENTUM_SAMPLE_SIZE = 5; type SwipeBounds = { left: number; top: number; width: number; height: number }; @@ -17,6 +21,8 @@ type SwipeGesture = direction: HistoryDirection; distance: number; deltas: number[]; + travelX: number; + travelY: number; y: number; bounds: SwipeBounds; } @@ -52,11 +58,19 @@ function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): bo return false; } +function isVerticalScroll(travelX: number, travelY: number): boolean { + return ( + travelX + travelY >= SWIPE_DOMINANCE_DISTANCE && travelX <= SWIPE_HORIZONTAL_DOMINANCE * travelY + ); +} + function lockSwipeAxis( pending: Extract, ): Exclude { const { path, sumX, sumY } = pending; - if (Math.abs(sumX) <= Math.abs(sumY)) return { kind: "ignored" }; + if (Math.abs(sumX) <= Math.abs(sumY) || isVerticalScroll(Math.abs(sumX), Math.abs(sumY))) { + return { kind: "ignored" }; + } if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { return { kind: "ignored" }; } @@ -68,6 +82,8 @@ function lockSwipeAxis( direction, distance: Math.abs(sumX), deltas: [], + travelX: Math.abs(sumX), + travelY: Math.abs(sumY), y: pending.y, bounds: readMainContentBounds(), }; @@ -134,6 +150,12 @@ export function HistorySwipeNavigation() { } else { const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX; if (event.deltaX === 0 && event.deltaY === 0) return release(); + gesture.travelX += Math.abs(event.deltaX); + gesture.travelY += Math.abs(event.deltaY); + if (isVerticalScroll(gesture.travelX, gesture.travelY)) { + gesture = { kind: "ignored" }; + return hideIndicator(); + } gesture.deltas = [...gesture.deltas.slice(1 - MOMENTUM_SAMPLE_SIZE), delta]; if (isMomentumTail(gesture.deltas)) return release(); gesture.distance = Math.max(0, gesture.distance + delta); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 5dc65e57f1ca3..dd12cedfbdefd 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -265,11 +265,15 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); - it("forwards address-bar focus from a focused desktop page", async () => { + it("forwards address-bar focus and zoom from a focused desktop page", async () => { setup(); await using _shortcut = await renderShortcut(); expect(state.setShortcuts).toHaveBeenLastCalledWith( - expect.arrayContaining([expect.objectContaining({ command: "preview.focusUrl" })]), + expect.arrayContaining( + ["preview.focusUrl", "preview.zoomIn", "preview.zoomOut", "preview.resetZoom"].map( + (command) => expect.objectContaining({ command }), + ), + ), ); }); }); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 7ecc10110f1fc..dfb68fe27e80a 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -50,6 +50,9 @@ const PREVIEW_FORWARDED_COMMANDS = [ "rightPanel.toggle", "rightPanel.toggleMaximized", "preview.focusUrl", + "preview.zoomIn", + "preview.zoomOut", + "preview.resetZoom", "preview.find", ] as const; diff --git a/apps/web/src/components/RightPanelSheet.browser.test.tsx b/apps/web/src/components/RightPanelSheet.browser.test.tsx new file mode 100644 index 0000000000000..c99e1e218b41c --- /dev/null +++ b/apps/web/src/components/RightPanelSheet.browser.test.tsx @@ -0,0 +1,16 @@ +import { expect, it } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../test/render"; +import { RightPanelSheet } from "./RightPanelSheet"; + +it("names the open right-panel dialog", async () => { + await using _screen = await render( + {}}> +
Panel content
+
, + ); + const dialog = page.getByRole("dialog"); + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).not.toHaveAccessibleName(""); +}); diff --git a/apps/web/src/components/RightPanelSheet.tsx b/apps/web/src/components/RightPanelSheet.tsx index 0cad2af5009d8..56846307b83da 100644 --- a/apps/web/src/components/RightPanelSheet.tsx +++ b/apps/web/src/components/RightPanelSheet.tsx @@ -1,6 +1,6 @@ import { type ReactNode } from "react"; -import { Sheet, SheetPopup } from "./ui/sheet"; +import { Sheet, SheetHeader, SheetPopup, SheetTitle } from "./ui/sheet"; export function RightPanelSheet(props: { animationDurationMs: number; @@ -24,6 +24,9 @@ export function RightPanelSheet(props: { keepMounted className="w-[min(42vw,28rem)] min-w-80 max-w-[28rem] max-[760px]:w-[min(88vw,24rem)] max-[760px]:min-w-0 wco:mt-(--workspace-topbar-height) wco:h-[calc(100%-var(--workspace-topbar-height))] wco:max-h-[calc(100%-var(--workspace-topbar-height))]" > + + Workspace panel + {props.children} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index 9fd2758747533..850b9cb8174f5 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -4,10 +4,14 @@ import { ThreadId, type ScopedThreadRef, type FilesystemEntryMetadata, + type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { Atom, AsyncResult } from "effect/reactivity"; import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface"; import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry"; +import { useRightPanelStore } from "../rightPanelStore"; +import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { extractTerminalLinks } from "../terminal-links"; import { expect, it, vi } from "vite-plus/test"; import { act, fakeTimers, render } from "../../test/render"; @@ -110,6 +114,7 @@ function Drawer(props: { threadRef: ScopedThreadRef; cwd?: string; onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; + keybindings?: ResolvedKeybindingsConfig; }) { return ( {}} onAddTerminalContext={() => {}} - keybindings={[]} + keybindings={props.keybindings ?? []} /> ); } @@ -149,6 +154,8 @@ function setup() { fixture.pendingSurfaces = []; fixture.surfaceOptions = []; fixture.metadata.clear(); + useRightPanelStore.setState(useRightPanelStore.getInitialState()); + useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); return { original, other }; } @@ -170,6 +177,42 @@ it("closes an exited terminal on its own thread after navigating to one reusing expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]); }); +// Thread navigation defaults have no `!terminalFocus`, so they apply in a focused terminal. +it("hands thread navigation shortcuts from a focused terminal back to the app", async () => { + const { other: threadRef } = setup(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + useRightPanelStore.getState().openBrowser(threadRef, null); + await using _screen = await render( + {}} + keybindings={compileResolvedKeybindingsConfig([ + ...DEFAULT_KEYBINDINGS, + { key: "ctrl+r", command: "thread.next", when: "!previewOpen" }, + { key: "ctrl+g", command: "thread.previous", when: "terminalOpen" }, + ])} + />, + ); + await act(async () => { + fixture.pendingSurfaces.shift()?.(); + }); + const terminalHandles = (key: string, code: string, shiftKey = true) => + fixture.surfaceOptions + .at(-1)! + .beforeKey(new KeyboardEvent("keydown", { key, code, ctrlKey: true, shiftKey })); + + expect([terminalHandles("{", "BracketLeft"), terminalHandles("}", "BracketRight")]).toEqual([ + false, + false, + ]); + expect(terminalHandles("C", "KeyC")).toBe(true); + // Sidebar sees the open preview and the closed drawer and rejects these, so the shell keeps them. + expect([terminalHandles("r", "KeyR", false), terminalHandles("g", "KeyG", false)]).toEqual([ + true, + true, + ]); +}); + it("only activates terminal paths confirmed to exist on their environment", async () => { const { other: threadRef } = setup(); const key = (path: string) => JSON.stringify([threadRef.environmentId, path]); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 6312f88bb2754..2e08462eba471 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -57,8 +57,7 @@ import { } from "~/terminal/ghostty/surface"; import { type GhosttyColor, type GhosttyTheme } from "~/terminal/ghostty/core"; import { useOpenInPreferredEditor } from "../editorPreferences"; -import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; -import { isTerminalUrl } from "../terminal-links"; +import { isTerminalUrl, resolveTerminalLinkTarget } from "../terminal-links"; import { isDiffToggleShortcut, isTerminalClearShortcut, @@ -66,6 +65,7 @@ import { isTerminalSplitShortcut, isTerminalSplitVerticalShortcut, isTerminalToggleShortcut, + isThreadNavigationShortcut, terminalDeleteShortcutData, terminalNavigationShortcutData, } from "../keybindings"; @@ -91,6 +91,7 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview"; import { useAtomCommand } from "../state/use-atom-command"; import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; import { observeResize } from "../lib/observeResize"; +import { threadShortcutContext } from "./Sidebar.logic"; import { consumePendingTerminalFocus, focusTerminal, @@ -524,7 +525,7 @@ function TerminalSessionViewport({ linkPath !== null && canOpenHostEditor && canReadFilesystem ? getFileMetadataQueryAtom( environmentId, - resolvePathLinkTarget(linkPath, cwd), + resolveTerminalLinkTarget(linkPath, cwd), cwd, metadataThreadRef, ) @@ -545,7 +546,7 @@ function TerminalSessionViewport({ return false; const query = getFileMetadataQueryAtom( environmentId, - resolvePathLinkTarget(text, cwd), + resolveTerminalLinkTarget(text, cwd), cwd, metadataThreadRef, ); @@ -575,6 +576,7 @@ function TerminalSessionViewport({ const hasHandledExitRef = useRef(false); const selectionActionRequestIdRef = useRef(0); const readKeybindings = useEffectEvent(() => keybindings); + const readThreadShortcutContext = useEffectEvent(() => threadShortcutContext(threadRef)); const handleSessionExited = useEffectEvent(() => { if (hasTerminalWriteAccess()) onSessionExited(); }); @@ -938,7 +940,11 @@ function TerminalSessionViewport({ isTerminalSplitShortcut(event, currentKeybindings, options) || isTerminalSplitVerticalShortcut(event, currentKeybindings, options) || isTerminalNewShortcut(event, currentKeybindings, options) || - isDiffToggleShortcut(event, currentKeybindings, options) + isDiffToggleShortcut(event, currentKeybindings, options) || + // Match Sidebar's context, or a key it will reject skips the shell. + isThreadNavigationShortcut(event, currentKeybindings, { + context: { ...readThreadShortcutContext(), terminalFocus: true }, + }) ) { return false; } @@ -1004,7 +1010,7 @@ function TerminalSessionViewport({ ); return; } - const target = resolvePathLinkTarget(text, cwd); + const target = resolveTerminalLinkTarget(text, cwd); void (async () => { const result = await openTerminalPath(target); if (result._tag === "Success" || isAtomCommandInterrupted(result)) { diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx index 3c49f7a88f45b..db46999708043 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -1,9 +1,11 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import remarkParse from "remark-parse"; +import { unified } from "unified"; import { describe, expect, it, vi } from "vite-plus/test"; import { render } from "../../../test/render"; -import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; +import { ChatMarkdownAssetImage, markdownImageCopy } from "./ChatMarkdownMedia"; // Every evaluation of the URL query is one mint: the first read, then one per refresh. const assetQuery = vi.hoisted(() => ({ mints: 0 })); @@ -84,3 +86,14 @@ describe("ChatMarkdownAssetImage", () => { expect(assetQuery.mints).toBe(2); }); }); + +describe("markdownImageCopy", () => { + it("copies an image whose path has a space as Markdown that is still that image", () => { + // Raw HTML and sources reach the copy with the space unencoded. + const copied = markdownImageCopy("Shot", "/work/my shot.png", undefined); + const [block] = unified().use(remarkParse).parse(copied).children; + const images = + block?.type === "paragraph" ? block.children.filter((node) => node.type === "image") : []; + expect(images.map((image) => decodeURI(image.url))).toEqual(["/work/my shot.png"]); + }); +}); diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx index c810890ebf96b..ce1745a6e51fd 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx @@ -37,7 +37,19 @@ export function markdownImageCopy(alt: string, src: string, title: string | unde const escapedAlt = alt.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]"); const titleSuffix = title === undefined ? "" : ` "${title.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; - return `![${escapedAlt}](${src}${titleSuffix})`; + return `![${escapedAlt}](${markdownDestination(src)}${titleSuffix})`; +} + +// Raw HTML sources keep spaces and parentheses that a bare Markdown destination cannot hold. +function markdownDestination(src: string): string { + if (!/[\s<>()]/.test(src)) return src; + const escaped = src + .replaceAll("\\", "\\\\") + .replaceAll("<", "\\<") + .replaceAll(">", "\\>") + .replaceAll("\n", "%0A") + .replaceAll("\r", "%0D"); + return `<${escaped}>`; } /** diff --git a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx index 9dadb999da85e..bb03e19dd130b 100644 --- a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx @@ -7,12 +7,14 @@ import { render } from "../../../test/render"; import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext"; import { ComposerContextPermissions } from "../ComposerContextPermissions"; import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { focusRequestedPermission, markOpenToPermissions, useComposerMenuProps, } from "./composerEventScope"; import { ComposerFooterModeControls, ComposerPermissionsSection } from "./ComposerFooterControls"; +import { ComposerPickerFooter } from "./ComposerModelEffort"; import { runtimeModeConfig, runtimeModeOptions } from "./runtimeModeConfig"; const options = runtimeModeOptions.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); @@ -95,6 +97,49 @@ it("returns focus to the editor after a pick", async () => { await vi.waitFor(() => expect(handle.focusAtEnd).toHaveBeenCalled()); }); +// Mirrors the model picker: a composer popover whose footer nests the Permissions menu. +function PickerWithPermissions() { + const [mode, setMode] = useState("full-access"); + const composerMenuProps = useComposerMenuProps(); + return ( + <> +

Timeline

+ + Model + + + + + + ); +} + +it("on a touch tablet, tapping outside the Permissions menu leaves the editor unfocused", async () => { + const realMatchMedia = window.matchMedia.bind(window); + using _touch = vi + .spyOn(window, "matchMedia") + .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query)); + const { handle, ui } = withComposer(); + await using screen = await render(ui, { router: false }); // no routes involved + await userEvent.click(screen.getByRole("button", { name: "Model" })); + await userEvent.click(page.getByRole("button", { name: "Permissions: Full access" })); + const fullAccess = page.getByRole("menuitemradio", { name: "Full access" }); + await expect.element(fullAccess).toBeInTheDocument(); + const permissionsTrigger = page.getByRole("button", { name: "Permissions: Full access" }); + // The first outside tap closes the Permissions menu, the second the picker around it. + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + await expect.element(fullAccess).not.toBeInTheDocument(); + await userEvent.click(screen.getByText("Timeline")); + await expect.element(permissionsTrigger).not.toBeInTheDocument(); + // Focusing the editor after a tap opens the on-screen keyboard on Android tablets. + expect(handle.focusAtEnd).not.toHaveBeenCalled(); +}); + it("opens on the checked permission when composer.mode marked the trigger", async () => { await using screen = await render(, { router: false }); // no routes involved const trigger = screen.getByRole("button", { name: "More" }); diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index 91bf642fcb32f..e621f491527da 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -14,7 +14,7 @@ import { useNewThreadHandler } from "~/hooks/useHandleNewThread"; import { useOrderWhileOpen } from "~/hooks/useOrderWhileOpen"; import { useProjectPin } from "~/hooks/useProjectGroupUpdate"; import { useScratchProject } from "~/hooks/useScratchProject"; -import { isTriagePrompt } from "~/hooks/useStartTriage"; +import { isTriagePrompt } from "@t3tools/shared/triagePrompt"; import { useClientSettings } from "~/hooks/useSettings"; import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions"; import { diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx index f4a7fbfb7c133..5aeb5c028cdeb 100644 --- a/apps/web/src/components/chat/LinkRequestCard.tsx +++ b/apps/web/src/components/chat/LinkRequestCard.tsx @@ -297,7 +297,7 @@ function LinkRequestDialog(props: { {steps.length > 1 && !useExisting ? ( - Create a link on {targetName}: Settings → Connections → Create link, then - paste its code here. + Create a link on {targetName}: Settings → Sharing & access → Authorized + clients → Create link, then paste its code here. )} @@ -393,7 +393,7 @@ function LinkRequestDialog(props: { {useExisting ? (

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

) : null} {error !== null ? ( diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.browser.test.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.browser.test.tsx new file mode 100644 index 0000000000000..903c6346f758b --- /dev/null +++ b/apps/web/src/components/chat/MarkdownCodeBlock.browser.test.tsx @@ -0,0 +1,35 @@ +import { expect, it } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import "../../index.css"; + +import { ensureClientSettingsHydrated, persistClientSettingsPatch } from "../../hooks/useSettings"; +import { MarkdownCodeBlock } from "./MarkdownCodeBlock"; + +const setWordWrap = (wordWrap: boolean) => + act(() => persistClientSettingsPatch({ wordWrap }, async () => {})); + +it("follows a changed word wrap default while mounted", async () => { + await ensureClientSettingsHydrated(); + await setWordWrap(false); + await using screen = await render( + +
+        a long line
+      
+
, + { router: false }, // The code block reads no route state. + ); + const block = () => screen.container.querySelector(".chat-markdown-codeblock"); + expect(block()?.getAttribute("data-wrap")).toBe("false"); + + await setWordWrap(true); + await expect.element(screen.getByRole("button", { name: "Disable line wrap" })).toBeVisible(); + expect(block()?.getAttribute("data-wrap")).toBe("true"); +}); diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index 7992ce2e6f76b..24a7d083c7025 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -3,7 +3,7 @@ import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; -import { getClientSettings } from "../../hooks/useSettings"; +import { useClientSettings } from "../../hooks/useSettings"; import type { DiffThemeName } from "../../lib/diffRendering"; import { createIncrementalHighlightedDocument, @@ -161,7 +161,9 @@ export function MarkdownCodeBlock({ cause, ), }); - const [wrapped, setWrapped] = useState(() => getClientSettings().wordWrap); + const defaultWrapped = useClientSettings((settings) => settings.wordWrap); + const [wrapOverride, setWrapOverride] = useState(null); + const wrapped = wrapOverride ?? defaultWrapped; const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines"; const copyLabel = copied ? "Copied" : "Copy code"; const command = code.trim(); @@ -227,7 +229,7 @@ export function MarkdownCodeBlock({ variant={wrapped ? "secondary" : "ghost-muted"} size="icon-xs" aria-pressed={wrapped} - onClick={() => setWrapped((value) => !value)} + onClick={() => setWrapOverride(!wrapped)} aria-label={wrapLabel} /> } diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 3907ef764c5a5..77da83deffe2b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -2,7 +2,7 @@ import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; import { flushSync } from "react-dom"; import { AudioPreview } from "../files/AudioPreview"; -import { cdp, page } from "vite-plus/test/browser"; +import { cdp, page, userEvent } from "vite-plus/test/browser"; import { ComposerContextId, EnvironmentId, @@ -37,6 +37,7 @@ import { environmentThreadDetails } from "../../state/threads"; import { act, fakeTimers, render, stubGlobal } from "../../../test/render"; import { ChangedFilesCard } from "./ChangedFilesTree"; import { MessagesTimeline } from "./MessagesTimeline"; +import { createWorkspaceFocusController, workspaceAreaProps } from "../../lib/workspaceFocus"; import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic"; import { makeStreamingTimelineFixture } from "../../test-fixtures"; import { @@ -565,6 +566,38 @@ describe("MessagesTimeline messages", () => { await expectHeadingInView("Last turn", "Turn 118:"); }); + it("scrolls from the keyboard once F6 moves into the conversation", async () => { + setup(); + const props = baseProps(); + const entries = Array.from({ length: 40 }, (_, index) => + message(`Turn ${index}:\n\n${"x ".repeat(200)}`, {}, `turn-${index}`), + ); + await using _screen = await renderElement( + <> +
+ +
+
+ +
+ , + ); + const focus = createWorkspaceFocusController(document); + using _focus = { [Symbol.dispose]: focus.dispose }; + const viewport = props.listRef.current!.getScrollableNode()!; + await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0)); + const atEnd = viewport.scrollTop; + page.getByRole("button", { name: "Send" }).element().focus(); + await userEvent.keyboard("{F6}"); + focus.move(-1); + expect(viewport).toHaveAttribute("data-workspace-keyboard-focus"); + await userEvent.keyboard("{PageUp}"); + await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); @@ -828,6 +861,25 @@ describe("MessagesTimeline messages", () => { expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); }); + it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { + const source = + "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; + await using screen = await renderTimeline([ + message(source), + message("Drop ~~the old plan~~", {}, "message-2"), + message(source, { role: "assistant" }, "assistant-1"), + ]); + const [user, doubleTilde, assistant] = screen.container.querySelectorAll( + "[data-timeline-row-kind=message]", + ); + expect(user?.textContent).toContain(source); + expect(user?.querySelector("del")).toBeNull(); + expect(doubleTilde?.querySelector("del")?.textContent).toBe("the old plan"); + expect(assistant?.querySelector("del")?.textContent).toBe( + "/folder-a/skills/x, then follow the guide (", + ); + }); + it("renders sanitized raw HTML in assistant messages", async () => { await using screen = await renderTimeline([ message( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index ac091176ce426..eb4bd6fea6efd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1468,6 +1468,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ onScroll={handleScroll} onItemSizeChanged={scheduleMinimapRefresh} onMetricsChange={scheduleMinimapRefresh} + // Keyboard scrolling only moves the focused element; F6 and clicks land here. + tabIndex={-1} + data-workspace-focus-default className={cn( "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]", topFadeEnabled && "topbar-scroll-fade", diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index ae55a3214da9e..c4593d2f6c5e1 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,6 +1,9 @@ import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { remarkEnableOrderedListNumbers } from "@t3tools/shared/markdownPipeline"; +import { + CHAT_USER_MARKDOWN_REMARK_PLUGINS, + remarkEnableOrderedListNumbers, +} from "@t3tools/shared/markdownPipeline"; import { findRevealRef } from "./markdownFindContext"; import { type EnvironmentId, @@ -1200,7 +1203,10 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE_REMARK_PLUGINS = [ + ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, + remarkEnableOrderedListNumbers, +]; const UserMessageBody = memo(function UserMessageBody(props: { text: string; diff --git a/apps/web/src/components/chat/composerEventScope.ts b/apps/web/src/components/chat/composerEventScope.ts index a0271b4a8257d..b71c338e61ec9 100644 --- a/apps/web/src/components/chat/composerEventScope.ts +++ b/apps/web/src/components/chat/composerEventScope.ts @@ -1,4 +1,5 @@ import { useComposerHandleContext } from "../../composerHandleContext"; +import { useMediaQuery } from "../../hooks/useMediaQuery"; const COMPOSER_FLOATING_LAYER_SELECTOR = [ '[data-composer-drawer-layer="true"]', @@ -11,19 +12,22 @@ export const composerFloatingLayerProps = { export function useComposerMenuProps() { const composerRef = useComposerHandleContext(); + const isCoarsePointer = useMediaQuery({ pointer: "coarse" }); return { ...composerFloatingLayerProps, - finalFocus: composerRef - ? () => { - const activeElement = document.activeElement; - if (activeElement !== document.body && !isInsideComposerFloatingLayer(activeElement)) { + // Focusing the editor on a touch device opens the on-screen keyboard, so the menu keeps its own focus return. + finalFocus: + composerRef && !isCoarsePointer + ? () => { + const activeElement = document.activeElement; + if (activeElement !== document.body && !isInsideComposerFloatingLayer(activeElement)) { + return false; + } + composerRef.current?.focusAtEnd(); return false; } - composerRef.current?.focusAtEnd(); - return false; - } - : undefined, + : undefined, }; } diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts index 7620bf8611020..8090157604986 100644 --- a/apps/web/src/components/chat/useComposerMenuItems.ts +++ b/apps/web/src/components/chat/useComposerMenuItems.ts @@ -1,3 +1,7 @@ +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "@t3tools/client-runtime/thread-pull-requests"; import { matchComposerEnvironmentItems, matchComposerThreadItems, @@ -327,10 +331,17 @@ export function useComposerMenuItems({ ) { const exactPullRequest = exactPullRequestLookup.data?.number === pullRequestTriggerNumber - ? [exactPullRequestLookup.data] + ? [ + { + ...exactPullRequestLookup.data, + // Only the host: the URL's full repository path would not match the project's selector. + host: legacyThreadPullRequestKey(exactPullRequestLookup.data).host, + }, + ] : []; const matches = /^\d*$/u.test(composerTrigger.query) ? filterComposerPullRequestMatches({ + keyOf: threadPullRequestKeyOf, entries: [...exactPullRequest, ...(pullRequestLookup.data?.entries ?? [])], linked: linkedPullRequests, projectId: pullRequestProjectId, @@ -339,6 +350,7 @@ export function useComposerMenuItems({ limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, }) : withLinkedComposerPullRequestsFirst({ + keyOf: threadPullRequestKeyOf, matches: rankPullRequestMatches( (pullRequestLookup.data?.entries ?? []).filter((entry) => { if ( @@ -363,7 +375,7 @@ export function useComposerMenuItems({ limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, }); return matches.map((pullRequest) => ({ - id: `pull-request:${pullRequest.projectId}:${pullRequest.repository}:${pullRequest.number}`, + id: `pull-request:${pullRequest.projectId}:${threadPullRequestKeyOf(pullRequest)}`, type: "pull-request", pullRequest: { number: pullRequest.number, diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index b59408a35a7cb..3f67e8c9c7987 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -14,16 +14,24 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { flushSync } from "react-dom"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { deriveLogicalProjectKeyFromSettings, selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { useComposerDraftStore, DraftId } from "../../composerDraftStore"; import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments"; +import { currentClientMetadata } from "../../connection/platform"; import { useProjects } from "../../state/entities"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; import type { DraftSessionState } from "../../composerDraftStore"; import { loadBalancingSendWarning } from "./composerSend.logic"; import { appAtomRegistry } from "../../rpc/atomRegistry"; @@ -53,7 +61,8 @@ interface DraftEnvironmentRoutingInput { /** * Which machine an unsent draft runs on: automatic load balancing across the * project's machines, or a manual switch, which may first open a scratch - * project on the target machine. + * project on the target machine. A triage draft takes its session along: the + * target machine prepares one, and the playbook link follows. */ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) { const { @@ -76,6 +85,9 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) } = input; const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const getDraftSession = useComposerDraftStore((store) => store.getDraftSession); + const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); + const setPrompt = useComposerDraftStore((store) => store.setPrompt); + const prepareTriage = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false }); const setLogicalProjectDraftThreadId = useComposerDraftStore( (store) => store.setLogicalProjectDraftThreadId, ); @@ -284,7 +296,8 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) const request = { environmentId: target.environmentId, scope: environmentChangeScope }; environmentChangeRef.current = request; setBusyEnvironmentChange(null); - const retarget = (project: (typeof allProjects)[number]) => { + // `triagePrompt` is the prompt the target machine prepared for a triage draft. + const retarget = (project: (typeof allProjects)[number], triagePrompt?: string) => { const currentDraft = getDraftSession(draftId); if ( environmentChangeRef.current !== request || @@ -296,6 +309,12 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) currentDraft.projectId !== originalDraft.projectId ) return; + if (triagePrompt !== undefined) { + // Read now, so text typed while the machine prepared the session is kept. + const prompt = getComposerDraft(draftId)?.prompt ?? ""; + const nextPrompt = replaceTriagePlaybookLink(prompt, triagePrompt); + if (nextPrompt !== prompt) setPrompt(draftId, nextPrompt); + } const projectRef = scopeProjectRef(target.environmentId, project.id); if (activeProjectIsScratch) { setLogicalProjectDraftThreadId( @@ -316,21 +335,45 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) if (environmentChangeRef.current === request) environmentChangeRef.current = null; setBusyEnvironmentChange((busy) => (busy === request ? null : busy)); }; - if (target.projectId !== null) { - const project = allProjects.find( - (project) => - project.environmentId === target.environmentId && project.id === target.projectId, - ); - if (project) retarget(project); + const knownProject = allProjects.find( + (project) => + project.environmentId === target.environmentId && project.id === target.projectId, + ); + // The playbook and context files exist only on the machine that prepared them. + const followsTriage = isTriagePrompt(getComposerDraft(draftId)?.prompt ?? ""); + if (target.projectId !== null && !(knownProject && followsTriage)) { + if (knownProject) retarget(knownProject); finish(); return; } + const prepareTriagePrompt = async () => { + const prepared = await prepareTriage({ + environmentId: target.environmentId, + input: { client: currentClientMetadata() }, + }); + if (prepared._tag === "Success") return prepared.value.prompt; + if (!isAtomCommandInterrupted(prepared)) { + const error = squashAtomCommandFailure(prepared); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not switch machine", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return null; + }; + const switchMachine = async () => { + const triagePrompt = followsTriage ? await prepareTriagePrompt() : undefined; + if (triagePrompt === null) return; + const project = + knownProject ?? + (await openScratchProject(target.environmentId, "Could not switch machine")); + if (project) retarget(project, triagePrompt); + }; setBusyEnvironmentChange(request); - void openScratchProject(target.environmentId, "Could not switch machine") - .then((project) => { - if (project) retarget(project); - }) - .finally(finish); + void switchMachine().finally(finish); }; const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index 0320dd6d6bb18..3118cd3ec7100 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -18,6 +18,7 @@ import { toastManager } from "../ui/toast"; import { act, render } from "../../../test/render"; import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "../../lib/terminalContext"; import { environmentContextRecord, environmentContextReference, @@ -327,6 +328,32 @@ describe("useQueuedRunEdit", () => { ); }); + it("adds terminal context to the queued message being edited", async () => { + const { hook } = setup(); + await using _screen = await render(view(THREAD_A, "queued", hook)); + await beginChangedEdit(hook); + const target = requireHook(hook).draftTarget; + const inserted = useComposerDraftStore.getState().insertTerminalContext( + target, + `changed${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}`, + { + id: "terminal-context-1", + threadId: THREAD_A.threadId, + createdAt: "2026-01-01T00:00:00.000Z", + terminalId: "default", + terminalLabel: "Terminal 1", + lineStart: 3, + lineEnd: 3, + text: "hello", + }, + 0, + ); + expect(inserted).toBe(true); + expect( + useComposerDraftStore.getState().getComposerDraft(target)?.terminalContexts, + ).toHaveLength(1); + }); + it("keeps an open edit when the user leaves the thread and comes back", async () => { const { hook } = setup(); await using screen = await render(view(THREAD_A, "queued", hook)); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index e5e5c11dff755..0ed3f9228940f 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -28,7 +28,7 @@ import { Atom } from "effect/reactivity"; import type { RefObject } from "react"; import { useAssetUrls } from "../../assets/assetUrls"; import { - DraftId, + queuedRunEditDraftId, useComposerDraftStore, type ComposerFileAttachment, type ComposerImageAttachment, @@ -95,10 +95,6 @@ interface QueuedRunEditContent { const isDraftOwnedRecord = (record: ComposerContextRecord) => record.kind === "thread" || record.kind === "environment"; -function queuedEditDraftTarget(routeThreadRef: ScopedThreadRef, runId: RunId) { - return DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`); -} - async function submitQueuedRunEdit(input: { readonly environmentId: EnvironmentId; readonly draftTarget: ComposerThreadTarget; @@ -216,7 +212,7 @@ export function useQueuedRunEdit(input: { const editing = activeThreadId === null ? null : storedEdit; const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true; const draftTarget = - editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId); + editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId); const imageResources = (editing?.existingAttachments ?? []) .filter((attachment) => attachment.type === "image") @@ -239,12 +235,12 @@ export function useQueuedRunEdit(input: { const clearEditDraft = (runId: RunId) => useComposerDraftStore .getState() - .clearComposerContent(queuedEditDraftTarget(routeThreadRef, runId)); + .clearComposerContent(queuedRunEditDraftId(routeThreadRef, runId)); const beginEdit = useStableCallback((request: EditQueuedRunRequest) => { if (activeThreadId === null) return; if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId); - const target = queuedEditDraftTarget(routeThreadRef, request.runId); + const target = queuedRunEditDraftId(routeThreadRef, request.runId); const sentText = stripAttachmentOnlyBootstrapPrompt(request.text); const context = serverProjection?.messages.find( (message) => message.id === request.messageId, @@ -294,7 +290,7 @@ export function useQueuedRunEdit(input: { // unscoped and names the thread: the user may be anywhere by now. onRunLeftQueue: (_, edit) => { const recovery = recoverQueuedMessageEdit({ - editTarget: queuedEditDraftTarget(routeThreadRef, edit.runId), + editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId), threadTarget: threadDraftTarget, originalText: edit.originalText, removedExistingAttachment: edit.removedExistingAttachment === true, diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 4ee9011dad47d..b36940287c2c7 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -17,6 +17,8 @@ const state = vi.hoisted(() => ({ file: null as ProjectReadFileResult | null, optimistic: null as ProjectReadFileResult | null, writeFile: vi.fn(), + assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState, + mintUrl: vi.fn<() => Promise>(), })); vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({ @@ -58,6 +60,15 @@ vi.mock(import("~/hooks/useTheme"), async (original) => ({ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ useWorkspaceMutationRefresh: vi.fn(), })); +vi.mock(import("~/assets/assetUrls"), async (original) => ({ + ...(await original()), + useAssetUrlRefresh: () => state.mintUrl, + useAssetUrlState: () => state.assetUrl, +})); +// The Word engine compiles a large WebAssembly bundle; these tests only need the URL it loads. +vi.mock(import("./OfficeFilePreview"), () => ({ + OfficeFilePreview: ({ src }: { src: string }) =>
{src}
, +})); vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <> })); vi.mock(import("./FileBrowserPanel"), () => ({ default: () => ( @@ -109,6 +120,9 @@ function setup() { localStorage.setItem(keys[1]!, "true"); state.file = null; state.optimistic = null; + state.assetUrl = { _tag: "Loading" }; + let mints = 0; + state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`); state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined)); return { [Symbol.dispose]() { @@ -131,7 +145,7 @@ function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of return filePreview("tasks.md"); } -function filePreview(relativePath: string) { +function filePreview(relativePath: string, workspaceMutationId: string | null = null) { return ( ); } +function documentPreview(workspaceMutationId: string, fileRevision: string) { + state.file = null; + state.assetUrl = { + _tag: "Success", + url: "/assets/report.docx", + expiresAt: Number.MAX_SAFE_INTEGER, + fileRevision, + }; + return filePreview("report.docx", workspaceMutationId); +} + function deepActiveElement() { let active = document.activeElement; while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; @@ -279,6 +304,65 @@ describe("rendered Markdown task saves", () => { }); }); +describe("workspace document previews", () => { + it("keeps an unchanged document loaded when another workspace change lands", async () => { + using _settings = setup(); + await using screen = await render(documentPreview("mutation-1", "revision-1")); + const preview = screen.getByTestId("office-preview"); + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); + const loaded = preview.element(); + + await screen.rerender(documentPreview("mutation-2", "revision-1")); + + expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce(); + expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true); + }); + + it("keeps an unchanged document mounted while its revision check reloads", async () => { + using _settings = setup(); + await using screen = await render(documentPreview("mutation-1", "revision-1")); + const preview = screen.getByTestId("office-preview"); + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); + const loaded = preview.element(); + + state.assetUrl = { _tag: "Loading" }; + await screen.rerender(filePreview("report.docx", "mutation-1")); + await screen.rerender(documentPreview("mutation-1", "revision-1")); + + expect( + state.mintUrl, + "a reloading revision check re-minted the document URL", + ).toHaveBeenCalledOnce(); + expect( + screen.container.contains(loaded), + "a reloading revision check remounted the document", + ).toBe(true); + }); + + it("reloads the document when its URL can no longer be minted", async () => { + using _settings = setup(); + await using screen = await render(documentPreview("mutation-1", "revision-1")); + const preview = screen.getByTestId("office-preview"); + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); + + state.assetUrl = { _tag: "Failure" }; + await screen.rerender(filePreview("report.docx", "mutation-2")); + + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2"); + }); + + it("loads the new bytes when the document itself changes", async () => { + using _settings = setup(); + await using screen = await render(documentPreview("mutation-1", "revision-1")); + const preview = screen.getByTestId("office-preview"); + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); + + await screen.rerender(documentPreview("mutation-2", "revision-2")); + + await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2"); + }); +}); + describe("rendered Markdown select all", () => { it("selects only the rendered file, including after a task toggle", async () => { using _settings = setup(); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 0ec8e94facc92..9d842f0d85d4c 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -398,6 +398,64 @@ function WorkspaceAudioPreview(props: { ); } +function WorkspaceDocumentPreview(props: { + readonly environmentId: EnvironmentId; + readonly threadRef: ScopedThreadRef; + readonly draft: boolean; + readonly document: boolean; + readonly absolutePath: string; + readonly workspaceRoot: string; + readonly name: string; + readonly workspaceMutationId: string | null; + readonly refreshRevision: number; +}) { + const resource = + props.draft && props.document + ? { + _tag: "draft-workspace-file" as const, + cwd: props.workspaceRoot, + path: props.absolutePath, + } + : { + _tag: "media-file" as const, + threadId: props.threadRef.threadId, + path: props.absolutePath, + ...(props.document ? {} : { disposition: "attachment" as const }), + }; + // Drafts keep reloading on every workspace mutation, as before. + const revisioned = resource._tag === "media-file"; + const assetUrl = useAssetUrlState( + props.environmentId, + revisioned ? resource : null, + props.workspaceMutationId ?? undefined, + ); + const resolved = + assetUrl._tag === "Success" ? (assetUrl.fileRevision ?? props.workspaceMutationId) : undefined; + // A reconnect reports Loading and keeps the last revision, so the open file stays loaded; + // a failure (say the file was deleted) remounts so the preview shows its error. + const [shown, setShown] = useState(resolved); + if (resolved !== undefined && resolved !== shown) setShown(resolved); + const revision = !revisioned + ? props.workspaceMutationId + : assetUrl._tag === "Failure" + ? `failure:${props.workspaceMutationId}` + : (resolved ?? shown); + // Waiting on the first revision keeps the preview from mounting twice when it opens. + if (revisioned && revision === undefined && assetUrl._tag === "Loading") { + return ; + } + return ( + + ); +} + function clampFileLine(contents: string, requestedLine: number): number { let lineCount = 1; for (let index = 0; index < contents.length; index += 1) { @@ -1538,24 +1596,17 @@ export default function FilePreviewPanel({ ) : relativePath && absolutePath && (isDocument || file.readError?.failure === "binary_file") ? ( - ) : relativePath && file.error && file.data === null ? (
void; onForward: () => void; onRefresh: () => void; + onStopLoading: () => void; onSubmit: (url: string) => void; onOpenInBrowser?: (() => void) | undefined; onCapture?: ((record: boolean) => void) | undefined; @@ -61,6 +62,7 @@ export function PreviewChromeRow({ onBack, onForward, onRefresh, + onStopLoading, onSubmit, onOpenInBrowser, onCapture, @@ -135,7 +137,7 @@ export function PreviewChromeRow({
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 16807e878bb2f..f7cb3082491e9 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -334,6 +334,11 @@ export function PreviewView({ else if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId); }; + const handleStopLoading = () => { + if (isServerTab) serverSurfaceRef.current?.stopLoading(); + else if (previewBridge && runtimeTabId) void previewBridge.stopLoading(runtimeTabId); + }; + const adjustServerTab = async (change: Omit) => { if (!tabId) return; const result = await adjust({ @@ -948,6 +953,9 @@ export function PreviewView({ // shortcuts from the guest as menu actions instead. const unsubscribeMenu = window.desktopBridge?.onMenuAction((action) => { if (action === "preview.focusUrl") onPreviewAction("focus-url"); + if (action === "preview.zoomIn") onPreviewAction("zoom-in"); + if (action === "preview.zoomOut") onPreviewAction("zoom-out"); + if (action === "preview.resetZoom") onPreviewAction("reset-zoom"); if (action === "preview.find") onPreviewAction("find"); }); return () => { @@ -981,6 +989,7 @@ export function PreviewView({ onBack={handleBack} onForward={handleForward} onRefresh={handleRefresh} + onStopLoading={handleStopLoading} onSubmit={(next) => void handleSubmitUrl(next)} onOpenInBrowser={tabId ? handleOpenInBrowser : undefined} onCapture={previewBridge && tabId && !isServerTab ? handleCapture : undefined} diff --git a/apps/web/src/components/preview/openPreviewSession.test.ts b/apps/web/src/components/preview/openPreviewSession.test.ts index 005d44d9468c7..9acfd0eb6c050 100644 --- a/apps/web/src/components/preview/openPreviewSession.test.ts +++ b/apps/web/src/components/preview/openPreviewSession.test.ts @@ -97,6 +97,30 @@ describe("openPreviewSession", () => { }); }, ); + + it.each(["new tab", "link"] as const)( + "opens a server tab from a %s with the default zoom and appearance", + async (entryPoint) => { + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + browserDefaultZoomFactor: 0.8, + browserDefaultAppearance: "dark", + }); + const openPreview = vi.fn(async () => AsyncResult.success(snapshot)); + + if (entryPoint === "link") { + vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server"); + await openUrlInPreview({ openPreview, threadRef, url: "https://t3.chat/" }); + } else { + await openPreviewSession({ openPreview, threadRef, runtime: "server" }); + } + + expect(openPreview).toHaveBeenCalledExactlyOnceWith({ + environmentId: threadRef.environmentId, + input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }), + }); + }, + ); }); describe("openUrlInPreview from a link", () => { diff --git a/apps/web/src/components/preview/openPreviewSession.ts b/apps/web/src/components/preview/openPreviewSession.ts index 99dc6c3e572c4..6c372888de5a2 100644 --- a/apps/web/src/components/preview/openPreviewSession.ts +++ b/apps/web/src/components/preview/openPreviewSession.ts @@ -45,7 +45,9 @@ export async function openPreviewSession( ...(input.url === undefined ? {} : { url: input.url }), viewport: input.viewport ?? defaults.viewport, profileId: input.profileId ?? defaults.profileId, - ...(runtime === undefined || runtime === "desktop" ? {} : { runtime }), + ...(runtime === undefined || runtime === "desktop" + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); if (result._tag === "Failure") { diff --git a/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts b/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts index 069a5782e7fdb..ab11752a66fef 100644 --- a/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts +++ b/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts @@ -3,6 +3,8 @@ import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import type { OpenPreviewMutation } from "~/browser/openFileInPreview"; +import * as previewRuntime from "~/browser/previewRuntime"; import { openTerminalLinkInPreview } from "./openTerminalLinkInPreview"; vi.mock("~/previewStateStore", () => ({ @@ -36,6 +38,8 @@ vi.mock("~/browser/browserLinkTarget", () => ({ const hydratedDefaults = { viewport: { _tag: "fixed", width: 1280, height: 720 } as const, profileId: "work", + zoomFactor: 0.8, + appearance: "dark", }; const threadRef = { @@ -69,4 +73,24 @@ describe("openTerminalLinkInPreview", () => { expect(reportError).not.toHaveBeenCalled(); expect(fallbackToBrowser).not.toHaveBeenCalled(); }); + + it("opens a server tab with the default zoom and appearance", async () => { + vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server"); + const openPreview = vi.fn(async () => + AsyncResult.failure(Cause.interrupt()), + ); + + await openTerminalLinkInPreview({ + url: "https://t3.chat/", + threadRef, + openPreview, + fallbackToBrowser: vi.fn(), + forceBrowser: false, + }); + + expect(openPreview).toHaveBeenCalledExactlyOnceWith({ + environmentId: threadRef.environmentId, + input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }), + }); + }); }); diff --git a/apps/web/src/components/preview/openTerminalLinkInPreview.ts b/apps/web/src/components/preview/openTerminalLinkInPreview.ts index d160c1ee7ea61..867cc528f9ae8 100644 --- a/apps/web/src/components/preview/openTerminalLinkInPreview.ts +++ b/apps/web/src/components/preview/openTerminalLinkInPreview.ts @@ -64,7 +64,9 @@ export async function openTerminalLinkInPreview( url: input.url, viewport: defaults.viewport, profileId: defaults.profileId, - ...(runtime === undefined ? {} : { runtime }), + ...(runtime === undefined + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); if (result._tag === "Failure") { diff --git a/apps/web/src/components/preview/usePreviewBridge.test.ts b/apps/web/src/components/preview/usePreviewBridge.test.ts index 736ac7d743c32..be98eebcd91b1 100644 --- a/apps/web/src/components/preview/usePreviewBridge.test.ts +++ b/apps/web/src/components/preview/usePreviewBridge.test.ts @@ -1,9 +1,9 @@ -import type { DesktopPreviewTabState } from "@t3tools/contracts"; +import { ThreadId, type DesktopPreviewTabState } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore"; -import { createCaptureActivity, projectDesktopState } from "./usePreviewBridge"; +import { buildReportInput, createCaptureActivity, projectDesktopState } from "./usePreviewBridge"; const favicon = { dataUrl: "data:image/png;base64,AAAA", @@ -30,6 +30,41 @@ function state(navStatus: DesktopPreviewTabState["navStatus"]): DesktopPreviewTa }; } +describe("buildReportInput", () => { + it("reports title changes at the same URL without repeating unrelated desktop updates", () => { + const threadId = ThreadId.make("thread-1"); + const tabId = "tab-1"; + const url = "http://localhost:3000/app"; + let lastReport = { + lastReportedUrl: null as string | null, + lastReportedKind: null as DesktopPreviewTabState["navStatus"]["kind"] | null, + lastReportedTitle: null as string | null, + }; + const report = (nextState: DesktopPreviewTabState) => { + const result = buildReportInput({ threadId, tabId, state: nextState, ...lastReport }); + if (result) { + lastReport = result; + } + return result?.input.navStatus ?? null; + }; + + const loaded = state({ kind: "Success", url, title: "Original title" }); + expect(report(loaded)).toEqual({ _tag: "Success", url, title: "Original title" }); + expect(report(loaded)).toBeNull(); + + const retitled = state({ kind: "Success", url, title: "Updated title" }); + expect(report(retitled)).toEqual({ _tag: "Success", url, title: "Updated title" }); + expect( + report({ + ...retitled, + audible: true, + controller: "human", + updatedAt: "2026-08-09T00:00:01.000Z", + }), + ).toBeNull(); + }); +}); + describe("projectDesktopState", () => { it("shows a retained icon only while the current document has the captured origin", () => { expect( diff --git a/apps/web/src/components/preview/usePreviewBridge.ts b/apps/web/src/components/preview/usePreviewBridge.ts index 92bc9b29b35c3..6973f22f7dd3b 100644 --- a/apps/web/src/components/preview/usePreviewBridge.ts +++ b/apps/web/src/components/preview/usePreviewBridge.ts @@ -54,6 +54,7 @@ export function usePreviewBridge(input: { const lastReportedUrl = useRef(null); const lastReportedKind = useRef(null); + const lastReportedTitle = useRef(null); const lastDesktopNavStatus = useRef(null); const captureActivity = useRef | null>(null); const handleStateChange = useEffectEvent( @@ -74,10 +75,12 @@ export function usePreviewBridge(input: { state, lastReportedUrl: lastReportedUrl.current, lastReportedKind: lastReportedKind.current, + lastReportedTitle: lastReportedTitle.current, }); if (!reported || serverDriven) return; lastReportedUrl.current = reported.lastReportedUrl; lastReportedKind.current = reported.lastReportedKind; + lastReportedTitle.current = reported.lastReportedTitle; void reportStatus({ environmentId: stableThreadRef.environmentId, input: reported.input, @@ -89,6 +92,7 @@ export function usePreviewBridge(input: { if (!previewBridge || typeof window === "undefined") return; lastReportedUrl.current = null; lastReportedKind.current = null; + lastReportedTitle.current = null; lastDesktopNavStatus.current = null; const activity = createCaptureActivity(runtimeTabId); captureActivity.current = activity; @@ -134,25 +138,28 @@ export function projectDesktopState(state: DesktopPreviewTabState): DesktopPrevi }; } -function buildReportInput(args: { +export function buildReportInput(args: { readonly threadId: ThreadId; readonly tabId: string; readonly state: DesktopPreviewTabState; readonly lastReportedUrl: string | null; readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null; + readonly lastReportedTitle: string | null; }): { readonly input: PreviewReportStatusInput; readonly lastReportedUrl: string; readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"]; + readonly lastReportedTitle: string; } | null { - const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args; + const { threadId, tabId, state, lastReportedUrl, lastReportedKind, lastReportedTitle } = args; const status = state.navStatus; if (status.kind === "Idle") return null; const sameAsLast = status.kind !== "LoadFailed" && status.kind === lastReportedKind && - status.url === lastReportedUrl; + status.url === lastReportedUrl && + status.title === lastReportedTitle; if (sameAsLast) return null; const base = { @@ -175,6 +182,7 @@ function buildReportInput(args: { }, lastReportedUrl: status.url, lastReportedKind: "LoadFailed", + lastReportedTitle: status.title, }; } return { @@ -184,5 +192,6 @@ function buildReportInput(args: { }, lastReportedUrl: status.url, lastReportedKind: status.kind, + lastReportedTitle: status.title, }; } diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index febf82441f514..49eb9063c50c0 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -7,7 +7,12 @@ import { capitalizeTerm, sourceControlClients, } from "@t3tools/client-runtime/source-control-clients"; -import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs"; +import type { + CodeViewItem, + DiffLineAnnotation, + FileDiffMetadata, + SelectedLineRange, +} from "@pierre/diffs"; import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react"; import type { EnvironmentId, @@ -20,6 +25,7 @@ import type { PullRequestReviewThread, PullRequestThreadCommentsResult, } from "@t3tools/contracts"; +import { SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts"; import { ChevronDownIcon, ChevronRightIcon, @@ -64,6 +70,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { fileDiffRows } from "@t3tools/client-runtime/review-guide-tour"; import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; +import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { orderDiffFiles } from "./pullRequestFileOrder.logic"; import { buildFileDiffRenderKey, @@ -88,6 +95,7 @@ import { pullRequestEnvironment } from "~/state/pullRequests"; import { useEnvironmentQuery } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; +import { ChatMarkdownAssetImage } from "../chat/ChatMarkdownMedia"; import { DiffPanelLoadingState } from "../DiffPanelShell"; import { useDiffWorkerPool } from "../DiffWorkerPoolProvider"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; @@ -144,6 +152,7 @@ interface ReviewAnnotationGroup { readonly threads: ReadonlyArray; readonly pending: ReadonlyArray; readonly draft: boolean; + readonly image?: { readonly url: string; readonly path: string }; } type ReviewAnnotation = DiffLineAnnotation; @@ -395,7 +404,8 @@ function PullRequestCodeTab({ const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : "expanded"); const diffLayout = settings.diffLayout; - const [wordWrap, setWordWrap] = useState(settings.wordWrap); + const [wordWrapOverride, setWordWrapOverride] = useState(null); + const wordWrap = wordWrapOverride ?? settings.wordWrap; const [ignoreWhitespace, setIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); const [fileTreeOpen, setFileTreeOpen] = useLocalStorage( PULL_REQUEST_FILE_TREE_STORAGE_KEY, @@ -636,6 +646,20 @@ function PullRequestCodeTab({ return placed; })(); + const imageRevision = commit ?? detail.headSha; + const rawFileUrl = sourceControlClients.find(detail.provider)?.rawFileUrl; + const repositoryUrl = sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl; + // Hosts send no patch for an image, so its expanded row shows the file at this revision. + const imagePreviewUrl = (fileDiff: FileDiffMetadata, path: string) => + fileDiff.hunks.length === 0 && + fileDiff.type !== "deleted" && + isWorkspaceImagePreviewPath(path) && + imageRevision !== undefined && + rawFileUrl !== undefined && + repositoryUrl !== undefined + ? rawFileUrl({ repositoryUrl, sha: imageRevision, path }) + : null; + const annotatedFiles = files.map((fileDiff) => { const fileKey = buildFileDiffRenderKey(fileDiff); const path = resolveFileDiffPath(fileDiff); @@ -688,6 +712,14 @@ function PullRequestCodeTab({ lineNumber: group.line, metadata: { threads: group.threads, pending: group.pending, draft: group.draft }, })); + const imageUrl = imagePreviewUrl(fileDiff, path); + if (imageUrl !== null) { + annotations.push({ + side: "additions", + lineNumber: 0, + metadata: { threads: [], pending: [], draft: false, image: { url: imageUrl, path } }, + }); + } return { fileKey, path, @@ -698,7 +730,7 @@ function PullRequestCodeTab({ annotations .map( ({ side, lineNumber, metadata }) => - `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending + `${side}:${lineNumber}:${metadata.image?.url ?? ""}:${metadata.draft ? "d" : ""}:${metadata.pending .map((comment) => `${comment.id}:${comment.body}`) .join(",")}:${metadata.threads .map( @@ -1084,6 +1116,20 @@ function PullRequestCodeTab({ const renderAnnotation = (...[annotation]: CodeViewAnnotationArgs) => ( // Folded resolved conversations alone add no row, so the code reads straight through.
+ {annotation.metadata.image ? ( +
+ +
+ ) : null} {annotation.metadata.pending.map((comment) => ( setWordWrap(checked)} + onCheckedChange={(checked) => setWordWrapOverride(checked)} > Wrap lines @@ -1386,7 +1432,7 @@ function PullRequestCodeTab({ size="sm" pressed={wordWrap} onPressedChange={(pressed) => { - setWordWrap(Boolean(pressed)); + setWordWrapOverride(Boolean(pressed)); }} /> } diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 212da0d088fe3..1b95a1a563aab 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -305,7 +305,7 @@ export function ReviewThreadCard({ contentEditable={false} onPointerDown={(event) => event.stopPropagation()} > -
+
{thread.isResolved ? ( ) : ( diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx index 19c6cb75c5ac5..8ecb158a8f2d0 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx @@ -1,9 +1,17 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { + DEFAULT_CLIENT_SETTINGS, + SourceControlProviderKind, + type ClientSettings, +} from "@t3tools/contracts"; import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; -const state = vi.hoisted(() => ({ update: vi.fn(), canUpdate: true })); +const state = vi.hoisted(() => ({ + update: vi.fn(), + canUpdate: true, + timestampFormat: "locale" as "locale" | "12-hour" | "24-hour", +})); vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), @@ -14,6 +22,13 @@ vi.mock(import("~/state/session"), async (original) => ({ readEnvironmentScope: () => true, useEnvironmentScope: () => true, })); +vi.mock(import("~/hooks/useSettings"), async (original) => ({ + ...(await original()), + useClientSettings: ((select?: (settings: ClientSettings) => unknown) => { + const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: state.timestampFormat }; + return select ? select(settings) : settings; + }) as never, +})); vi.mock(import("~/state/pullRequests"), async (original) => { const actual = await original(); const { Atom } = await import("effect/reactivity"); @@ -35,6 +50,7 @@ function setup() { state.update.mockReset(); state.update.mockResolvedValue({ _tag: "Success", value: undefined }); state.canUpdate = true; + state.timestampFormat = "locale"; } import { act, render as renderUi } from "../../../test/render"; @@ -231,3 +247,26 @@ it("fixes an overview thread as its opening remark, since it has no line to atta await userEvent.click(screen.getByRole("button", { name: "Fix in a thread" })); expect(onFixFinding).toHaveBeenCalledWith({ kind: "comment", comment: remark }); }); + +it("shows a comment's exact time in the chosen 24-hour clock", async () => { + setup(); + state.timestampFormat = "24-hour"; + const createdAt = "2026-09-01T17:30:00Z"; + const comment = { + id: "10", + kind: "review-comment" as const, + body: "A remark", + author: { login: "reviewer", name: null, avatarUrl: null }, + createdAt, + url: null, + path: null, + reviewState: null, + }; + await using screen = await render({ ...detail, comments: [comment], commentCount: 1 }); + + await userEvent.hover(screen.container.querySelector(`time[datetime="${createdAt}"]`)!); + const expected = new Date(createdAt).toLocaleString(undefined, { hour12: false }); + await vi.waitFor(() => + expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(expected), + ); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 4b706ef7eafd5..3da06db5cd8b3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -34,6 +34,8 @@ import { useLocalStorage } from "~/hooks/useLocalStorage"; import { cn } from "~/lib/utils"; import { useOpenLink } from "~/browser/useOpenLink"; import { RelativeTime } from "~/components/RelativeTime"; +import { useClientSettings } from "~/hooks/useSettings"; +import { formatFullTimestamp } from "~/timestampFormat"; import { Button } from "../ui/button"; import { PullRequestEditButton } from "./PullRequestEditButton"; @@ -110,6 +112,7 @@ function CommentIdentity({ comment: PullRequestComment; detail: PullRequestDetailView; }) { + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const actor = comment.author; const profileUrl = actor ? sourceControlClients.get(detail.provider).authorProfileUrl(actor.login, detail.url) @@ -137,7 +140,7 @@ function CommentIdentity({ - {new Date(comment.createdAt).toLocaleString()} + {formatFullTimestamp(comment.createdAt, timestampFormat)} {comment.url ? " · Open comment on host" : ""} diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index d2326814c9abb..569d987fe3080 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -54,6 +54,7 @@ export const PULL_REQUEST_MERGE_METHOD_LABELS: Record { const confirmed = await (requestConfirmDialog( - `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Connections to end the session there too.`, + `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Sharing & access to end the session there too.`, { variant: "destructive" }, ) ?? Promise.resolve(false)); if (!confirmed) return; @@ -273,8 +273,8 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi Link an environment - Agents here can then launch, message and wait on threads there. It appears in that - environment's Connections, where it can be revoked. + Agents here can then launch, message and wait on threads there. It appears under + Authorized clients in that environment's Sharing & access, where it can be revoked. @@ -332,9 +332,7 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi value={pairingCode} onChange={(event) => setPairingCode(event.target.value)} placeholder={ - machine === null - ? "From that environment's Connections, or t3 pair there" - : "Paste the code" + machine === null ? "From Sharing & access there, or t3 pair" : "Paste the code" } disabled={busy} autoComplete="one-time-code" @@ -343,8 +341,8 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi /> {machine !== null ? ( - Create a link on {machine.label}: Settings → Connections → Create link, then - paste its code here. + Create a link on {machine.label}: Settings → Sharing & access → Authorized + clients → Create link, then paste its code here. ) : null} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx index 9576820832323..0d505c3250f11 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx @@ -132,7 +132,8 @@ vi.mock(import("../files/projectFilesQueryState"), async (original) => ({ getProjectFileQueryAtom: () => missingProjectFile, })); -import { useComposerDraftStore } from "../../composerDraftStore"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { assetEnvironment } from "../../state/assets"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; @@ -418,6 +419,37 @@ describe("project settings permissions", () => { expect(screen.router.state.location.href).toBe(initialHref); }); + it("moves a draft on the removed checkout to a remaining checkout of the group", async () => { + setup(); + const draftId = DraftId.make("draft-handed-off"); + const [primaryProject, remoteProject] = state.projects; + const drafts = useComposerDraftStore.getState(); + drafts.setLogicalProjectDraftThreadId( + "github.com/example/shared-repo", + scopeProjectRef(primaryId, primaryProject!.id), + draftId, + ); + // "Add to another machine" hands the open draft to the new checkout this way. + drafts.setDraftThreadContext(draftId, { + projectRef: scopeProjectRef(remoteId, remoteProject!.id), + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); + drafts.setPrompt(draftId, "keep this prompt"); + await using screen = await mountPanel(); + + await userEvent.click(removeCheckout(screen, "/work/remote")); + await vi.waitFor(() => expect(state.releaseUploads).toHaveBeenCalledOnce()); + + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + environmentId: primaryId, + projectId: primaryProject!.id, + }); + expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt).toBe( + "keep this prompt", + ); + }); + it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => { setup(); const confirmed = deferred(); diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index c1e15267234b3..3f370ce7108d3 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -362,6 +362,13 @@ function ProjectDetail({ if (checkProjectAccess(members, "Failed to remove project")) return; const draftStore = useComposerDraftStore.getState(); + const remainingMember = allMembers.find( + (candidate) => + !members.some( + (member) => + member.environmentId === candidate.environmentId && member.id === candidate.id, + ), + ); for (const member of members) { if (checkProjectAccess([member], "Failed to remove project")) return; const memberThreads = projectThreads.filter( @@ -388,7 +395,13 @@ function ProjectDetail({ memberThreads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)), ); const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef); - if (projectDraftThread) { + if (projectDraftThread && remainingMember) { + draftStore.setDraftThreadContext(projectDraftThread.draftId, { + projectRef: scopeProjectRef(remainingMember.environmentId, remainingMember.id), + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); + } else if (projectDraftThread) { draftStore.clearDraftThread(projectDraftThread.draftId); } draftStore.clearProjectDraftThreadId(projectRef); diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 915273a3b4090..05a7471d44e34 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -1096,13 +1096,13 @@ export function ProviderInstanceCard({
@@ -1147,7 +1147,7 @@ export function ProviderInstanceCard({
- + {projectOverride?.value !== undefined ? ( { }); }); +describe("EnvironmentProviderSettings provider list", () => { + it("selects a provider when its row is clicked near the edge", async () => { + await setup(); + await setProviders([provider()]); + await using _screen = await render(panel()); + const select = page.getByRole("button", { name: "Select Claude" }); + await expect.element(select).toHaveAttribute("aria-pressed", "false"); + const row = page.elementLocator(select.element().closest('[data-slot="settings-row"]')!); + + await userEvent.click(row, { position: { x: 3, y: 3 } }); + + await expect.element(select).toHaveAttribute("aria-pressed", "true"); + }); +}); + describe("EnvironmentProviderSettings instance removal", () => { it("resets a configured default instance only once the user confirms", async () => { await setup(); diff --git a/apps/web/src/components/sidebar/updateEverythingRun.test.ts b/apps/web/src/components/sidebar/updateEverythingRun.test.ts index f451eadc13b2d..c06ff106c1c30 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.test.ts +++ b/apps/web/src/components/sidebar/updateEverythingRun.test.ts @@ -1,7 +1,9 @@ +import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection"; import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; -import { Atom } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { environmentCatalog } from "~/connection/catalog"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { serverEnvironment } from "~/state/server"; import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction"; @@ -60,6 +62,28 @@ describe("startDesktopUpdateLaunchNotice", () => { } }); + it("retries the connection to a restarting server instead of waiting out its backoff", async () => { + const environmentId = EnvironmentId.make("backing-off-machine"); + using _connection = vi + .spyOn(environmentCatalog, "stateAtom") + .mockReturnValue( + Atom.make( + AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }), + ) as unknown as ReturnType, + ); + using retryNow = vi + .spyOn(environmentCatalog.retryNow, "run") + .mockResolvedValue(AsyncResult.success(undefined)); + const stop = relaunchWhileRestarting(environmentId); + try { + await vi.advanceTimersByTimeAsync(1_000); + expect(retryNow).toHaveBeenCalledWith(appAtomRegistry, environmentId); + } finally { + await vi.advanceTimersByTimeAsync(32 * 60 * 1000); + stop(); + } + }); + it("clears the restored state when the server never comes back", async () => { const environmentId = EnvironmentId.make("lost-machine"); const stateAtom = serverEnvironment.updateStateAtom(environmentId); diff --git a/apps/web/src/components/sidebar/updateEverythingRun.tsx b/apps/web/src/components/sidebar/updateEverythingRun.tsx index ff12f9093571e..ac07c82e91b83 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.tsx +++ b/apps/web/src/components/sidebar/updateEverythingRun.tsx @@ -1,11 +1,18 @@ import { useAtomValue } from "@effect/atom-react"; -import { serverUpdateStateAtom } from "@t3tools/client-runtime/state/server"; +import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection"; +import { + nudgeReconnectDuringUpdateRestart, + serverUpdateStateAtom, +} from "@t3tools/client-runtime/state/server"; import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { AsyncResult, Atom } from "effect/reactivity"; +import * as Stream from "effect/Stream"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { APP_VERSION } from "~/branding"; +import { environmentCatalog } from "~/connection/catalog"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { desktopUpdateStateAtom } from "~/state/desktopUpdate"; import { serverEnvironment } from "~/state/server"; @@ -308,6 +315,7 @@ function followHandedOffServers(servers: ReadonlyArray): void { if (settled) return; settled = true; clearTimeout(timer); + stopReconnectNudge(); queueMicrotask(() => unsubscribe()); appAtomRegistry.set(stateAtom, { status: "idle" }); releaseState(); @@ -329,6 +337,19 @@ function followHandedOffServers(servers: ReadonlyArray): void { () => settle(`Not back after ${HANDOFF_TIMEOUT_MS / 60_000} minutes`), server.startedAt + HANDOFF_TIMEOUT_MS - Date.now(), ); + const stopReconnectNudge = Effect.runCallback( + nudgeReconnectDuringUpdateRestart({ + stateChanges: AtomRegistry.toStream( + appAtomRegistry, + environmentCatalog.stateAtom(server.environmentId), + ).pipe( + Stream.map((state) => AsyncResult.getOrElse(state, () => AVAILABLE_CONNECTION_STATE)), + ), + retryNow: Effect.promise(() => + environmentCatalog.retryNow.run(appAtomRegistry, server.environmentId), + ).pipe(Effect.asVoid), + }), + ); const unsubscribe = appAtomRegistry.subscribe( serverEnvironment.configValueAtom(server.environmentId), (config) => { diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index d5f46398fa31c..8ec1c7a02afcd 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -523,6 +523,18 @@ function PoolBar({ index={position + 1} showAccountName={pool.columns.length > 1} /> + ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? ( +
+ + $0 cap +
) : null, )}
diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts index 3a93b2efa201c..e7ec86822a547 100644 --- a/apps/web/src/composer-logic.test.ts +++ b/apps/web/src/composer-logic.test.ts @@ -1,3 +1,4 @@ +import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches"; import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts"; import { @@ -331,30 +332,35 @@ describe("detectComposerTrigger", () => { describe("filterComposerPullRequestMatches", () => { const entries = [ { + host: "github.com", number: 7, projectId: "project-1", repository: "t3tools/t3code", updatedAt: "2026-09-01T12:00:00.000Z", }, { + host: "github.com", number: 8987, projectId: "project-1", repository: "T3Tools/T3Code", updatedAt: "2026-09-03T12:00:00.000Z", }, { + host: "github.com", number: 27, projectId: "project-1", repository: "t3tools/t3code", updatedAt: "2026-09-02T12:00:00.000Z", }, { + host: "github.com", number: 27, projectId: "project-1", repository: "t3tools/t3code", updatedAt: "2026-09-01T13:00:00.000Z", }, { + host: "github.com", number: 70, projectId: "project-2", repository: "t3tools/other", @@ -365,6 +371,7 @@ describe("filterComposerPullRequestMatches", () => { it("matches and de-duplicates number fragments within one repository, exact match first", () => { expect( filterComposerPullRequestMatches({ + keyOf: threadPullRequestKeyOf, entries, projectId: "project-1", repository: "t3tools/t3code", @@ -376,18 +383,21 @@ describe("filterComposerPullRequestMatches", () => { it("keeps an older exact match when newer substring matches would fill the limit", () => { const exact = { + host: "github.com", number: 7, projectId: "project-1", repository: "t3tools/t3code", updatedAt: "2020-01-01T00:00:00.000Z", }; const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({ + host: "github.com", number: 700 + index, projectId: "project-1", repository: "t3tools/t3code", updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`, })); const matches = filterComposerPullRequestMatches({ + keyOf: threadPullRequestKeyOf, entries: [...newerSubstringMatches, exact], projectId: "project-1", repository: "t3tools/t3code", diff --git a/apps/web/src/composer-markdown-source.ts b/apps/web/src/composer-markdown-source.ts index c4119b981b18c..c57985f12e345 100644 --- a/apps/web/src/composer-markdown-source.ts +++ b/apps/web/src/composer-markdown-source.ts @@ -221,9 +221,9 @@ function collapseRegion(tr: Transaction, region: TextRange, type: MarkType): voi function collapseMarkdownSource( tr: Transaction, keep: (region: TextRange) => boolean = () => false, -): void { +): TextRange[] { const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK]; - if (!type) return; + if (!type) return []; const regions: TextRange[] = []; for (const region of sourceRegions(tr.doc, type)) { const extended = withAdjacentDelimiters(tr.doc, region); @@ -235,6 +235,7 @@ function collapseMarkdownSource( if (keep(region)) tr.addMark(region.from, region.to, type.create()); else collapseRegion(tr, region, type); } + return regions; } function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) => number) { @@ -248,7 +249,14 @@ function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) /** Parses all shown source first, so a command that splits it keeps its styles. */ export const collapseShownMarkdownSource: Command = ({ tr }) => { - collapseMarkdownSource(tr); + const { selection } = tr; + const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK]; + const marks = tr.storedMarks ?? selection.$from.marks(); + const regions = collapseMarkdownSource(tr); + // A caret after the closing markers is outside the styles, though parsed text there is inclusive. + if (type && selection.empty && regions.some(({ to }) => to === selection.from)) { + tr.setStoredMarks(type.removeFromSet(marks)); + } return true; }; diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index f719780357a2f..68fdc2b2bca36 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -1545,6 +1545,21 @@ export function resolveComposerDraftKey( return threadKey.length > 0 ? threadKey : null; } +const QUEUED_RUN_EDIT_DRAFT_PREFIX = "queued-edit:"; + +// Thread and run ids both contain colons, so the run id is encoded to keep the thread key parseable. +export function queuedRunEditDraftId(threadRef: ScopedThreadRef, runId: string): DraftId { + return DraftId.make( + `${QUEUED_RUN_EDIT_DRAFT_PREFIX}${scopedThreadKey(threadRef)}:${encodeURIComponent(runId)}`, + ); +} + +function queuedRunEditThreadId(draftId: string): ThreadId | null { + if (!draftId.startsWith(QUEUED_RUN_EDIT_DRAFT_PREFIX)) return null; + const rest = draftId.slice(QUEUED_RUN_EDIT_DRAFT_PREFIX.length); + return parseScopedThreadKey(rest.slice(0, rest.lastIndexOf(":")))?.threadId ?? null; +} + function resolveComposerThreadId( state: ComposerThreadLookupState, target: ComposerThreadTarget, @@ -1556,7 +1571,10 @@ function resolveComposerThreadId( if (typeof normalizedTarget !== "string") { return normalizedTarget.threadId; } - return state.draftThreadsByThreadKey[normalizedTarget]?.threadId ?? null; + return ( + state.draftThreadsByThreadKey[normalizedTarget]?.threadId ?? + queuedRunEditThreadId(normalizedTarget) + ); } function getComposerDraftState( diff --git a/apps/web/src/connection/storage.browser.test.ts b/apps/web/src/connection/storage.browser.test.ts index 2b36f9827c84f..a107aa902469f 100644 --- a/apps/web/src/connection/storage.browser.test.ts +++ b/apps/web/src/connection/storage.browser.test.ts @@ -57,7 +57,7 @@ describe("IndexedDB query cache", () => { ); expect(keptBytes).toBeLessThanOrEqual(32 * 1024 * 1024); expect(yield* tabs[1]!.load(environmentId, "large-8")).toEqual(Option.some(answer)); - }).pipe(Effect.scoped), + }), ); it.effect("drops the older copy when an answer grows too large to keep", () => diff --git a/apps/web/src/connection/storage.test.ts b/apps/web/src/connection/storage.test.ts index 7afe2b1e8573f..1778111d3f4cb 100644 --- a/apps/web/src/connection/storage.test.ts +++ b/apps/web/src/connection/storage.test.ts @@ -282,6 +282,6 @@ describe("browser GitHub routing permissions", () => { ConnectionTransientError, ); expect(yield* second.get(entry)).toBe("off"); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/web/src/hooks/useStartTriage.ts b/apps/web/src/hooks/useStartTriage.ts index 7d6671bf3d22c..6ddc3904afdf1 100644 --- a/apps/web/src/hooks/useStartTriage.ts +++ b/apps/web/src/hooks/useStartTriage.ts @@ -4,7 +4,7 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import { type EnvironmentId, TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useRouter } from "@tanstack/react-router"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; @@ -26,9 +26,6 @@ const copyTriageCliCommand = () => }), ); -/** A draft is a triage draft while its message still links the playbook file. */ -export const isTriagePrompt = (prompt: string) => prompt.includes(`[${TRIAGE_PROMPT_FILE_NAME}](`); - /** * In-app `t3 triage`: the server writes the session files and starts cloning * the matching source, then a No project draft opens with the playbook linked. diff --git a/apps/web/src/index.css b/apps/web/src/index.css index b4597954cb764..0f9942e3295ee 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2624,11 +2624,19 @@ code { } /* A workspace area with no control of its own takes F6 focus itself; keep that visible. - workspaceFocus.ts marks those, since :focus-visible also matches a clicked area after a key press. */ + workspaceFocus.ts marks those, since :focus-visible also matches a clicked area after a key press. + The conversation's timeline takes it instead, and its top fade mask would hide its own ring. */ [data-workspace-area]:focus-visible { outline: none; } -[data-workspace-keyboard-focus]:focus { +[data-workspace-keyboard-focus]:focus, +[data-workspace-area="conversation"]:has( + .messages-timeline-scroll[data-workspace-keyboard-focus]:focus +) { outline: 2px solid var(--ring); outline-offset: -2px; } + +.messages-timeline-scroll:focus-visible { + outline: none; +} diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index d2f6a5e650417..849183b7a1a69 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -281,12 +281,24 @@ export function threadTraversalDirectionFromCommand( return null; } +export function isThreadNavigationShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + const command = resolveShortcutCommand(event, keybindings, options); + return ( + threadTraversalDirectionFromCommand(command) !== null || + threadJumpIndexFromCommand(command ?? "") !== null + ); +} + export function shouldShowThreadJumpHintsForModifiers( modifiers: ShortcutModifierStateLike, keybindings: ResolvedKeybindingsConfig, options?: ShortcutMatchOptions, ): boolean { - // Ghostty can write keys to the shell before window shortcuts run, regardless of the when clause. + // Holding a modifier is routine in a shell (Ctrl+C, Ctrl+R), so don't flash hints over it. if (resolveContext(options).terminalFocus) { return false; } diff --git a/apps/web/src/lib/addProjectToMachine.ts b/apps/web/src/lib/addProjectToMachine.ts index 2d3bdc5259c88..4143498832e53 100644 --- a/apps/web/src/lib/addProjectToMachine.ts +++ b/apps/web/src/lib/addProjectToMachine.ts @@ -21,6 +21,9 @@ import { sourceControlEnvironment } from "../state/sourceControl"; /** Matches the server's read cap: a larger file would arrive truncated. */ export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024; +/** The server lists at most this many ignored files, so one pick never exceeded it. */ +export const COPIED_FILES_MAX_COUNT = 200; + const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/; /** Env files are the ignored files people almost always want on a new machine. */ diff --git a/apps/web/src/lib/backgroundActivityReporter.test.ts b/apps/web/src/lib/backgroundActivityReporter.test.ts index bbb24ce1b8516..210403425bfcb 100644 --- a/apps/web/src/lib/backgroundActivityReporter.test.ts +++ b/apps/web/src/lib/backgroundActivityReporter.test.ts @@ -109,7 +109,7 @@ describe("layer", () => { yield* TestClock.adjust("25 seconds"); expect(calls).toBe(2); - }).pipe(Effect.scoped), + }), ); it.effect("keeps reporting after a report never settles", () => @@ -134,6 +134,6 @@ describe("layer", () => { yield* TestClock.adjust("25 seconds"); expect(calls).toBe(2); - }).pipe(Effect.scoped), + }), ); }); diff --git a/apps/web/src/lib/workspaceFocus.browser.test.ts b/apps/web/src/lib/workspaceFocus.browser.test.ts index 4674e02ea61fc..769423a512b2c 100644 --- a/apps/web/src/lib/workspaceFocus.browser.test.ts +++ b/apps/web/src/lib/workspaceFocus.browser.test.ts @@ -33,6 +33,15 @@ function setup() { }; } +/** Mirrors MessagesTimeline's scroller, which takes focus so the keyboard scrolls it. */ +function conversationScroller(height: number) { + const timeline = document.createElement("div"); + timeline.style.cssText = `height: ${height}px; overflow-y: auto`; + timeline.tabIndex = -1; + timeline.dataset.workspaceFocusDefault = ""; + return timeline; +} + describe("workspace area focus", () => { it("cycles in workspace order in both directions, independent of DOM order", () => { using fixture = setup(); @@ -42,7 +51,7 @@ describe("workspace area focus", () => { const composer = fixture.area("composer", 2); sidebar.button.focus(); fixture.controller.move(1); - // The conversation is a region; it takes focus itself rather than its first button. + // Without a timeline (an empty thread), the region takes focus rather than its first button. expect(document.activeElement).toBe(conversation.element); fixture.controller.move(1); expect(document.activeElement).toBe(composer.button); @@ -204,8 +213,7 @@ describe("workspace area focus", () => { it("does not scroll the conversation to an old control", () => { using fixture = setup(); const conversation = fixture.area("conversation", 1); - const timeline = document.createElement("div"); - timeline.style.cssText = "height: 50px; overflow-y: auto"; + const timeline = conversationScroller(50); const copy = document.createElement("button"); copy.textContent = "Copy"; timeline.append(copy, Object.assign(document.createElement("div"), { style: "height: 400px" })); @@ -217,10 +225,28 @@ describe("workspace area focus", () => { // Live follow moved the timeline to the newest output. timeline.scrollTop = 300; fixture.controller.move(-1); - expect(document.activeElement).toBe(conversation.element); + expect(document.activeElement).toBe(timeline); expect(timeline.scrollTop).toBe(300); }); + it("scrolls the conversation with the keyboard once an empty thread gets a timeline", async () => { + using fixture = setup(); + const conversation = fixture.area("conversation", 1); + conversation.button.remove(); + conversation.element.style.height = "200px"; + const composer = fixture.area("composer", 2); + composer.button.focus(); + fixture.controller.move(-1); + expect(document.activeElement).toBe(conversation.element); + fixture.controller.move(1); + const timeline = conversationScroller(200); + timeline.append(Object.assign(document.createElement("div"), { style: "height: 2000px" })); + conversation.element.append(timeline); + fixture.controller.move(-1); + await userEvent.keyboard("{ArrowDown}{PageDown}"); + await vi.waitFor(() => expect(timeline.scrollTop).toBeGreaterThan(0)); + }); + it.each([ ["panel", "panel", "removed"], ["conversation", "composer", "removed"], @@ -281,7 +307,9 @@ describe("workspace area focus", () => { bringBack.textContent = "Bring back"; content.append(bringBack); panel.element.append(content); - fixture.area("conversation", 1, content); + const timeline = conversationScroller(50); + timeline.append(Object.assign(document.createElement("div"), { style: "height: 400px" })); + fixture.area("conversation", 1, content).element.append(timeline); const composer = fixture.area("composer", 2, content); const editor = document.createElement("div"); editor.contentEditable = "true"; diff --git a/apps/web/src/lib/workspaceFocus.ts b/apps/web/src/lib/workspaceFocus.ts index 38abacd9a82a6..05dd8281dca05 100644 --- a/apps/web/src/lib/workspaceFocus.ts +++ b/apps/web/src/lib/workspaceFocus.ts @@ -100,18 +100,22 @@ function revealInScrollers(target: HTMLElement) { export function createWorkspaceFocusController(doc: Document) { const lastFocused = new Map(); let lastArea: string | undefined; - // An area that took focus itself from the keyboard. Chromium's :focus-visible also matches - // a clicked area after any later key press, so the ring and window return read this mark. + // An area that took focus itself from the keyboard, or the non-tabbable default (the + // conversation's scroller) standing in for it. Chromium's :focus-visible also matches a + // clicked area after any later key press, so the ring and window return read this mark. let keyboardArea: HTMLElement | undefined; let previousTarget: EventTarget | null = null; const unmarkKeyboardArea = () => { keyboardArea?.removeAttribute("data-workspace-keyboard-focus"); keyboardArea = undefined; }; - const markKeyboardArea = (area: HTMLElement) => { - if (!area.matches(":focus-visible")) return; - keyboardArea = area; - area.setAttribute("data-workspace-keyboard-focus", ""); + const standsInFor = (element: HTMLElement, area: HTMLElement) => + element === area || + (element.tabIndex < 0 && element.hasAttribute("data-workspace-focus-default")); + const markKeyboardArea = (target: HTMLElement) => { + if (!target.matches(":focus-visible")) return; + keyboardArea = target; + target.setAttribute("data-workspace-keyboard-focus", ""); }; const remember = (event: FocusEvent) => { if (event.target !== keyboardArea) unmarkKeyboardArea(); @@ -121,7 +125,7 @@ export function createWorkspaceFocusController(doc: Document) { if (!(event.target instanceof HTMLElement)) return; const area = workspaceArea(event.target); if (!area?.dataset.workspaceArea) return; - if (arrived && event.target === area) markKeyboardArea(area); + if (arrived && standsInFor(event.target, area)) markKeyboardArea(event.target); lastArea = area.dataset.workspaceArea; const key = area.dataset.workspaceFocusKey ?? lastArea; lastFocused.delete(key); @@ -141,11 +145,14 @@ export function createWorkspaceFocusController(doc: Document) { const belongs = (element: HTMLElement) => workspaceArea(element) === area && usable(element); // A side chat's message input sits in its own area inside the panel. Opening the // panel focuses it, but F6 visits that area on its own, so it moves past it here. + // A nested timeline stands in only for its own area, never ahead of that input. const preferred = Array.from( area.querySelectorAll( '[data-workspace-focus-default], [data-sidebar-row][aria-current="page"], [data-settings-section][aria-current="page"], .xterm-helper-textarea, [contenteditable="true"]', ), - ).find(nested ? usable : belongs); + ).find((element) => + nested && !standsInFor(element, area) ? usable(element) : belongs(element), + ); const fallback = Array.from(area.querySelectorAll(FOCUSABLE_SELECTOR)).find( (element) => element.tabIndex >= 0 && belongs(element), ); @@ -172,10 +179,14 @@ export function createWorkspaceFocusController(doc: Document) { ) : undefined; // Moving the timeline to an old control would also stop it following a running turn, - // so the conversation reuses a control only while it is still in view. + // so the conversation reuses a control only while it is still in view. A remembered + // area is only the fallback it was then, so controls mounted since take precedence. const isConversation = area.dataset.workspaceArea === "conversation"; const targets = new Set([ - previous && belongs(previous) && (!isConversation || isInScrollView(previous)) + previous && + previous !== area && + belongs(previous) && + (!isConversation || isInScrollView(previous)) ? previous : undefined, isConversation ? undefined : restored, @@ -192,7 +203,7 @@ export function createWorkspaceFocusController(doc: Document) { if (active === target || (active && target.contains(active))) { if (target !== area && !isConversation) revealInScrollers(target); // Focusing the already focused area fires no focusin, as when F6 has nowhere else to go. - if (target === area) markKeyboardArea(area); + if (standsInFor(target, area)) markKeyboardArea(target); return true; } } diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index da6d331ef9c0d..e85e77b416f27 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -198,6 +198,38 @@ describe("serializeRenderedMarkdownFragment", () => { expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line"); }); + it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { + // The shape ChatMarkdown renders for `> [!WARNING]\n> Back up first.`. + const callout = new FakeElement("DIV", [], { + role: "note", + "data-markdown-alert": "warning", + }).append( + new FakeElement("P", [], { + "data-thread-find-ignore": "true", + "data-markdown-alert-label": "", + }).append(new FakeElement("SVG", [], { "aria-hidden": "true" }), new FakeText("Warning")), + new FakeElement("P").append(new FakeText("Back up first.")), + ); + const container = new FakeElement("DIV").append(callout); + + expect(serializeRenderedMarkdownFragment(asNode(container))).toBe( + "> [!WARNING]\n> Back up first.", + ); + const insight = new FakeElement("DIV", [], { + role: "note", + "data-markdown-alert": "insight", + }).append( + new FakeElement("P", [], { + "data-thread-find-ignore": "true", + "data-markdown-alert-label": "", + }).append(new FakeText("Insight")), + new FakeElement("P").append(new FakeText("Caches are warm.")), + ); + expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(insight)))).toBe( + `★ Insight ${"─".repeat(37)}\nCaches are warm.\n${"─".repeat(49)}`, + ); + }); + it("preserves explicit ordered-list values and continues from resets when copying", () => { const list = new FakeElement("OL", [], { start: "0" }).append( new FakeElement("LI").append(new FakeText("A")), diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 10c83bf9a96bd..91f16c86535a6 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -10,6 +10,9 @@ const SANITIZED_HTML_SELECTOR = [ ...SKIPPED_CLASS_NAMES.map((className) => `.${className}`), ].join(", "); +const ALERT_ATTRIBUTE = "data-markdown-alert"; +const ALERT_LABEL = "data-markdown-alert-label"; + export interface MarkdownClipboardPayload { text: string; html: string; @@ -159,10 +162,21 @@ function serializeList(list: Element, ordered: boolean, inTableCell: boolean): s .join("\n")}\n\n`; } -function serializeBlockquote(quote: Element, inTableCell: boolean): string { - const content = outsideCode(serializeChildren(quote, inTableCell), (prose) => - prose.replace(/\n{3,}/g, "\n\n"), - ).trim(); +function serializeQuoteBody(quote: Element, inTableCell: boolean): string { + let content = ""; + for (const child of quote.childNodes) { + // A callout's rendered label stands for the marker its serializer writes. + if (child.nodeType === Node.ELEMENT_NODE && (child as Element).hasAttribute(ALERT_LABEL)) { + continue; + } + content += serializeNode(child, inTableCell); + } + return outsideCode(content, (prose) => prose.replace(/\n{3,}/g, "\n\n")).trim(); +} + +function serializeBlockquote(quote: Element, inTableCell: boolean, marker = ""): string { + const body = serializeQuoteBody(quote, inTableCell); + const content = marker && body ? `${marker}\n${body}` : marker || body; if (!content) return ""; const quoted = content .split("\n") @@ -171,6 +185,11 @@ function serializeBlockquote(quote: Element, inTableCell: boolean): string { return `${quoted}\n\n`; } +function serializeInsight(insight: Element, inTableCell: boolean): string { + const body = serializeQuoteBody(insight, inTableCell); + return `★ Insight ${"─".repeat(37)}\n${body ? `${body}\n` : ""}${"─".repeat(49)}\n\n`; +} + function serializeDetails(details: Element): string { const summary = details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ?? @@ -231,6 +250,9 @@ function serializeNode(node: Node, inTableCell = false): string { : escapeTablePipes(markdownCopy, inTableCell); } if (isSkippedElement(element)) return ""; + const alert = element.getAttribute(ALERT_ATTRIBUTE); + if (alert === "insight") return serializeInsight(element, inTableCell); + if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`); const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1]; if (headingLevel) { @@ -478,6 +500,13 @@ export function chatMarkdownClipboardPayload( } continue; } + // A range spanning exactly one callout's text clones its contents but not the callout. + const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`); + if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) { + const wrapper = callout.cloneNode(false) as Element; + wrapper.append(...container.childNodes); + container.replaceChildren(wrapper); + } const text = serializeRenderedMarkdownFragment(container); if (!text) continue; texts.push(text); diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 944117ee768e5..73cee1a33bb4d 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1391,7 +1391,7 @@ describe("HTML renders in the timeline", () => { ]); }); - it("hosts a captured MCP app in place, from any provider's tool", () => { + it("hosts a captured MCP app after its tool row, from any provider's tool", () => { const mcpApp = { attachmentId: "render-thread-app-html", server: "weather", @@ -1403,13 +1403,58 @@ describe("HTML renders in the timeline", () => { call.type === "dynamic_tool" ? { ...call, toolName: "weather.get_weather" } : call, ); expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({ - id: "render", + id: "mcp-app:render", itemId: "render", mcpApp, }); expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "mcp-app", "message"]); }); + it("keeps an MCP app call's tool row and output beside its app card", () => { + const mcpApp = { + attachmentId: "render-thread-app-html", + server: "repro", + tool: "aggregate_rum_events", + resourceUri: "ui://repro/dataviz", + }; + const result = { content: [{ type: "text", text: "Notice\nview\tcount\n/home\t42" }] }; + const call = renderCall("completed", { t3McpApp: mcpApp, result }); + const entries = turn( + call.type === "dynamic_tool" ? { ...call, toolName: "repro.aggregate_rum_events" } : call, + ); + expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({ mcpApp }); + const toolRows = entries.flatMap((entry) => + entry.kind === "work" && entry.entry.toolTitle === "repro.aggregate_rum_events" + ? [entry.entry] + : [], + ); + expect(toolRows).toMatchObject([{ toolData: { output: { result } } }]); + }); + + it("drops an MCP app card when an update removes the call's app", () => { + const mcpApp = { + attachmentId: "render-thread-app-html", + server: "repro", + tool: "aggregate_rum_events", + resourceUri: "ui://repro/dataviz", + }; + const call = (output: unknown) => ({ + ...renderCall("completed", output), + toolName: "repro.aggregate_rum_events", + }); + const result = { content: [{ type: "text", text: "rows" }] }; + const input = (output: unknown) => ({ + visibleTurnItems: [visible(command("before", 1)), visible(call(output))], + optimisticMessages: [], + }); + const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState( + input({ t3McpApp: mcpApp, result }), + ); + const nextInput = input({ result }); + const next = deriveTimelineEntriesFromVisibleTurnItemsWithState(nextInput, previous); + expect(next.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(nextInput)); + }); + it("hosts an MCP app whose call failed, as a form-deferring write does", () => { const mcpApp = { attachmentId: "render-thread-app-html", diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index d4b6432be762e..affe166d6d6c4 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -652,22 +652,6 @@ export function deriveTimelineEntriesFromVisibleTurnItems( continue; } - const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined; - if (mcpApp !== undefined) { - entries.push({ - id: item.id, - kind: "mcp-app", - createdAt, - runId: item.runId, - sourceThreadId: row.sourceThreadId, - itemId: row.sourceItemId, - revision: turnItemDetailRevision(item), - mcpApp, - ...attemptMetadata, - }); - continue; - } - if (STANDALONE_V2_ITEM_TYPES.has(item.type)) { entries.push({ id: item.id, @@ -686,6 +670,21 @@ export function deriveTimelineEntriesFromVisibleTurnItems( entry: projectedWorkEntry(row), ...attemptMetadata, }); + + const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined; + if (mcpApp !== undefined) { + entries.push({ + id: `mcp-app:${item.id}`, + kind: "mcp-app", + createdAt, + runId: item.runId, + sourceThreadId: row.sourceThreadId, + itemId: row.sourceItemId, + revision: turnItemDetailRevision(item), + mcpApp, + ...attemptMetadata, + }); + } } const retainedMessageIds = new Set([ @@ -870,6 +869,9 @@ function canRederiveInPlace( item.item.type !== "user_message" && item.item.type !== "assistant_message" && item.item.type !== "user_input_request" && + // An app call projects two entries; in-place reuse replaces one. + (previousItem.item.type !== "dynamic_tool" || + mcpAppFromToolItem(previousItem.item) === undefined) && ((input.anchoredMessages?.length ?? 0) === 0 || projectedItemCreatedAt(item) === projectedItemCreatedAt(previousItem)) ); diff --git a/apps/web/src/state/revisionedQuery.test.ts b/apps/web/src/state/revisionedQuery.test.ts index 7dda15de23009..7b21dd1d29aee 100644 --- a/apps/web/src/state/revisionedQuery.test.ts +++ b/apps/web/src/state/revisionedQuery.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vite-plus/test"; import { revisionedQuery } from "./revisionedQuery"; // A stand-in query that counts its fetches. -function setup() { +function setup(readQuery: (cache: Atom.Atom) => Atom.Atom = (cache) => cache) { let fetches = 0; // Node removal runs on the registry's scheduler; releasing flushes it so the // next mount of the same revision builds a fresh node, as a React remount does. @@ -15,10 +15,12 @@ function setup() { return () => {}; }, }); - const query = Atom.make(() => { - fetches += 1; - return fetches; - }).pipe(Atom.keepAlive); + const query = readQuery( + Atom.make(() => { + fetches += 1; + return fetches; + }).pipe(Atom.keepAlive), + ); const mount = async (revision: string | null | undefined) => { const release = registry.mount(revisionedQuery(query, revision)); // A stale read refetches in a microtask, after the render that read it. @@ -77,6 +79,17 @@ describe("revisionedQuery", () => { expect(fetches()).toBe(2); }); + it("counts a query as cached while the atom it reads through keeps the value", async () => { + // Like an environment query: its own node goes with its last reader, the cache stays. + const { mount, fetches } = setup((cache) => + Atom.transform(cache, (get) => get(cache), { initialValueTarget: cache }), + ); + + (await mount(undefined))(); + (await mount("mutation-1"))(); + expect(fetches()).toBe(2); + }); + it("does not refetch a cached query on a first read before any workspace change", async () => { const { mount, fetches } = setup(); diff --git a/apps/web/src/state/revisionedQuery.ts b/apps/web/src/state/revisionedQuery.ts index 73e18b36161d5..90c147b664741 100644 --- a/apps/web/src/state/revisionedQuery.ts +++ b/apps/web/src/state/revisionedQuery.ts @@ -6,8 +6,14 @@ import { Atom, type AtomRegistry } from "effect/reactivity"; const readRevisions = new WeakMap>(); // The registry keys serializable atoms' nodes by their key, not the atom. -const queryKey = (query: Atom.Atom) => - Atom.isSerializable(query) ? query[Atom.SerializableTypeId].key : query; +const hasNode = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom) => + registry.getNodes().has(Atom.isSerializable(atom) ? atom[Atom.SerializableTypeId].key : atom); + +// A query's own node can go with its last reader while the atom it takes its value from +// (an environment query's cache, on an idle TTL) still holds the value. +const isCached = (registry: AtomRegistry.AtomRegistry, query: Atom.Atom) => + hasNode(registry, query) || + (query.initialValueTarget !== undefined && hasNode(registry, query.initialValueTarget)); const makeRevisionedFamily = (query: Atom.Atom) => Atom.family((revision: string | null) => @@ -25,14 +31,14 @@ const makeRevisionedFamily = (query: Atom.Atom) => ? revisions.get(query) !== revision : // A reader without a revision may have cached it before the latest // workspace change; a query nobody has read yet fetches fresh anyway. - revision !== null && get.registry.getNodes().has(queryKey(query)); + revision !== null && isCached(get.registry, query); // Deferred: this builds while React renders, and a refresh would synchronously // re-render the query's other readers, which React rejects. if (stale) { const registry = get.registry; queueMicrotask(() => { // No node, as after the registry is disposed: nothing cached to refetch. - if (registry.getNodes().has(queryKey(query))) registry.refresh(query); + if (isCached(registry, query)) registry.refresh(query); }); } revisions.set(query, revision); diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index a0fb98529cf05..242df9ddcccd3 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -5,6 +5,7 @@ import { collectWrappedTerminalLinkLine, extractTerminalLinks, isTerminalUrl, + resolveTerminalLinkTarget, type TerminalBufferLineLike, } from "./terminal-links"; @@ -297,4 +298,38 @@ describe("resolvePathLinkTarget", () => { "/Users/julius/project/main.c:10:5", ); }); + + it.each([ + ["src/main.ts", "/repo/src/main.ts"], + ["/repo/src/main.ts", "/repo/src/main.ts"], + [String.raw`C:\repo\src\main.ts`, String.raw`C:\repo\src\main.ts`], + ["app/(auth)/page.tsx", "/repo/app/(auth)/page.tsx"], + ])("preserves a TypeScript compiler location on %s", (path, target) => { + const text = `${path}(42,7)`; + const links = extractTerminalLinks(`${text}: error TS2322: Type mismatch`); + expect(links).toEqual([{ kind: "path", text: `${path}:42:7`, start: 0, end: text.length }]); + expect(resolveTerminalLinkTarget(links[0]?.text ?? "", "/repo")).toBe(`${target}:42:7`); + }); + + it.each([ + [String.raw`PS C:\dev\folder (42,7)> `, String.raw`C:\dev\folder (42,7)`], + ["/tmp/report(42,7)", "/tmp/report(42,7)"], + ["src/Program.cs(3,10): error CS1002: x", "/repo/src/Program.cs"], + ])("preserves existing path targets in %s", (line, target) => { + const [link] = extractTerminalLinks(line); + expect(resolveTerminalLinkTarget(link?.text ?? "", "/repo")).toBe(target); + }); + + // regression: #36005 OSC 8 file URIs were joined onto the cwd as relative paths + it("does not resolve an OSC 8 file URI target against the cwd", () => { + expect(resolveTerminalLinkTarget("file:///var/tmp/report.txt", "/workspace/project")).toBe( + "/var/tmp/report.txt", + ); + expect( + resolveTerminalLinkTarget("file://remote.invalid/var/tmp/report.txt", "/workspace/project"), + ).not.toMatch(/^\/workspace\/project\//); + expect(resolvePathLinkTarget("file:notes.md", "/workspace/project")).toBe( + "/workspace/project/file:notes.md", + ); + }); }); diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index d77848a8c26b3..1d4366cc42748 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -1,3 +1,11 @@ +import { + formatFilePathPosition, + parseFileUrlHref, + resolvePathLinkTarget, + splitFilePathPosition, +} from "@t3tools/shared/fileLinks"; +import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks"; +import { stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path"; import { isMacPlatform } from "./lib/utils"; export type TerminalLinkKind = "url" | "path"; @@ -32,9 +40,9 @@ const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]* // Bare paths start only at a segment boundary: hover detection runs this on // every frame, so separator-free output must not be rescanned at every suffix. // For the same reason `]` needs its `[`: trimming a long run of `]` is quadratic. -// Parentheses count only before a slash, so `src/foo.ts(3,10)` stays a compiler location. +// Parenthesized path segments need a following slash to distinguish compiler locations. const FILE_PATH_PATTERN = - /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?]+|(?(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[\p{L}\p{M}\p{N}._ -]+[\\/])[^\r\n]*?|[\p{L}\p{M}\p{N}._ -]+\.[\p{L}\p{M}\p{N}_-]+(?::\d+){0,2})\1(?(?::\d+){0,2})/gu; const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/; @@ -98,7 +106,10 @@ function collectMatches( const candidate: TerminalLinkMatch = { kind, - text: trimmed, + text: + kind === "path" && /^:\s+(?:error|warning) TS\d+:/u.test(line.slice(start + trimmed.length)) + ? trimmed.replace(/\((\d+),(\d+)\)$/, ":$1:$2") + : trimmed, start, // A position outside quotes spans the closing quote in the terminal buffer. end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0), @@ -150,6 +161,18 @@ export function isTerminalUrl(value: string): boolean { return /^https?:\/\//iu.test(value); } +/** Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`. */ +export function resolveTerminalLinkTarget(text: string, cwd: string): string { + const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text) : null; + if (!fileUrl) return resolvePathLinkTarget(text, cwd); + return formatFilePathPosition( + splitFilePathPosition( + stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(fileUrl.path)), + fileUrl.hash, + ), + ); +} + export function collectWrappedTerminalLinkLine( bufferLineNumber: number, getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined, diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index d9901763e4abf..c23924e65d159 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -122,6 +122,13 @@ describe("GhosttyTerminalCore snapshots", () => { expect(terminalNavigationShortcutData(event, "Win32") ?? core.encodeKey(event)).toBe(expected); }); + it("keeps a leading U+FEFF in an unbracketed paste", async () => { + const core = await createCore(); + core.write("\x1b[?2004l"); + + expect(core.encodePaste("\ufeffsample")).toBe("\ufeffsample"); + }); + it.each([ { code: "", key: "Backspace", expected: "\x7f" }, { code: "Unidentified", key: "Backspace", expected: "\x7f" }, diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index 1fba7e00d30b8..fa6c932a96572 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -162,7 +162,7 @@ export interface GhosttyMouseInput { readonly anyButtonPressed: boolean; } -const decoder = new TextDecoder(); +const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); const encoder = new TextEncoder(); function blend(foreground: GhosttyColor, background: GhosttyColor): GhosttyColor { diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index abad91401ccbe..9da2f71e98be9 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -131,6 +131,13 @@ export function formatChatTimestampTooltip( return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`; } +export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { + return new Date(isoDate).toLocaleString( + undefined, + timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" }, + ); +} + export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { const date = parseTimestampDate(isoDate); if (!date) return ""; diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 80abc3f859cbf..804757e78307a 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -136,6 +136,12 @@ describe("parsePersistedState", () => { }); }); + it("keeps a persisted fast-forward merge method", () => { + expect( + parsePersistedState({ pullRequestMergeMethod: "fast-forward" }).pullRequestMergeMethod, + ).toBe("fast-forward"); + }); + it.each([undefined, 1])("ignores changed-file expansion version %s", (version) => { const parsed = parsePersistedState({ ...(version === undefined ? {} : { threadChangedFilesExpansionVersion: version }), diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index a94905ef518d4..b2ac1a508c7a6 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -1,5 +1,6 @@ import { Debouncer } from "@tanstack/react-pacer"; -import type { PullRequestMergeMethod } from "@t3tools/contracts"; +import { PullRequestMergeMethod } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { create } from "zustand"; import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; @@ -99,6 +100,8 @@ function sanitizeOptionalKey(value: unknown): string | null { return typeof value === "string" && value.length > 0 ? value : null; } +const isPullRequestMergeMethod = Schema.is(PullRequestMergeMethod); + function sanitizeTimestampRecord(value: unknown): Record { if (!value || typeof value !== "object") { return {}; @@ -114,10 +117,6 @@ function sanitizeTimestampRecord(value: unknown): Record { ); } -function isPullRequestMergeMethod(value: unknown): value is PullRequestMergeMethod { - return value === "merge" || value === "squash" || value === "rebase"; -} - export function parsePersistedState(parsed: PersistedUiState): UiState { const projectExpandedById = parsed.projectExpandedById === undefined diff --git a/docs/operations/scenarios.md b/docs/operations/scenarios.md index c49f23a4b2068..22b61bf25301b 100644 --- a/docs/operations/scenarios.md +++ b/docs/operations/scenarios.md @@ -41,8 +41,10 @@ adds one fixture for what e2e cannot know about T3 Code: - `t3.project(title, files)` creates a git repository and adds it as a project. - `t3.thread({ project, title, messages })` starts a thread and plays one replayed turn per - message before returning, so the thread has real history. `model` picks the recording. -- `t3.open(path)` opens the app, already signed in. + message before returning, so the thread has real history. `model` picks the recording. It + returns the thread, which `t3.open` takes. +- `t3.open(path)` opens the app, already signed in, at a path. `t3.open(thread)` opens it on a + thread. State is created through the app's own CLI, so it is real events and works on a base commit whose schema differs. New threads default to the replay agent's `showcase` recording: type a @@ -61,6 +63,30 @@ could not run. Keep `agent.act` and `agent.assert` out of scenarios: they call a model, and no model is configured. +### Getting to the screen + +Most scenarios that could not run stopped on the way to the screen the bug is on, not on the +bug. Three rules avoid that: + +- **Open by link, not by sidebar.** `await t3.open(thread)` lands on the thread + ([`thread-opens-by-link.e2e.ts`](../../scripts/scenarios/thread-opens-by-link.e2e.ts)), and + `await t3.open("/settings/general")` on a settings page. A sidebar row is a button that covers + its own title, so a tap on `getByText("Earlier work")` is intercepted. When the sidebar is what + the scenario is about, target the row's button: `screen.getByRole("button", "Earlier work")`. +- **Let `t3.open` do the navigating.** It waits until the pairing page has signed in before it + goes anywhere. A second `app.open` straight after the pairing link cancels the sign-in and + shows the pairing page again. +- **Seed before opening.** Create projects and threads first, then call `t3.open`. With no + project the app opens its first-run page instead of the one the scenario expects. + +The app starts with only `PATH`, `HOME` and the temp directory in its environment, whatever the +shell that ran the scenario has set. Name what it needs in `T3_SCENARIO_INHERIT_ENV`: exact +names or prefixes ending in `*`, separated by commas. + +```sh +T3_SCENARIO_INHERIT_ENV='SHELL,MY_FIXTURE_*' vp run scenarios:prove scripts/scenarios/name.e2e.ts --base main +``` + ## Run ```sh @@ -102,12 +128,27 @@ commits and compares the two reports. It prints, and writes to `scripts/.e2e/pro its commit, ready for a pull request description. `--upload-command` names a command that takes the capture paths and prints one URL per line. `--head` defaults to `HEAD`. -It exits 0 only when the scenario fails on base and passes on head, 1 when it ran and did not -prove the fix, and 2 when it could not run. A scenario that passes on base does not reproduce the -bug, and the verdict says so. +It exits 0 only when the scenario fails on base and passes on head, and 1 when it ran and did not +prove the fix. A scenario that passes on base does not reproduce the bug, and the verdict says so. + +Two more codes mean there is no verdict on the behavior, and `couldNotRun` in the proof says +which: + +- **3, `scenario`:** the app ran and the scenario stopped before its assertion, usually on a + control it did not find. Read that side's `message` and `steps`, fix the scenario, and run it + again. +- **2, `app`:** the app did not start or no test ran: a bad revision, a failed install, a port in + use. `scripts/.e2e/app.log` has the app's output. + +Each side's result is also written as it ends, to `scripts/.e2e/prove/base.json` and +`head.json`, so a run that is cut short keeps the side it finished. + +It runs the scenario on one target: iOS when the file imports `t3-mobile.ts`, web otherwise. +`--target web` or `--target ios` overrides that. The scenario and e2e always come from your checkout. Only the app comes from the commit under -test: a temporary worktree beside your checkout, installed with `vp i` and removed afterwards. A +test: a temporary worktree beside your checkout, installed with `vp i` and removed afterwards (one +left by a run that was killed is replaced). A commit that is your clean `HEAD` runs in place. So a new scenario can prove a fix against a base that predates it. diff --git a/docs/user/devices.md b/docs/user/devices.md index ac053b36c081f..3d5c66a9a307c 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -110,7 +110,7 @@ the environment’s own machine are skipped, since its devices are already local The first device listing installs pinned device tools on the host. SSH device hosts currently need macOS or Linux. To use devices on a Windows machine, run T3 Code on that machine and connect to its environment. -Node 22 or newer and npm must be available to non-interactive SSH commands. +Node 22.12 or newer and npm must be available to non-interactive SSH commands. T3 checks common Homebrew and Android SDK locations; custom installations need the appropriate PATH and ANDROID_HOME on the host. Android emulator video needs `ffmpeg` with libx264 on that host; physical Android devices use scrcpy and do diff --git a/docs/user/faq.md b/docs/user/faq.md index 77e0e53370e65..5c5b9a8d8368d 100644 --- a/docs/user/faq.md +++ b/docs/user/faq.md @@ -6,7 +6,7 @@ No. A harness is what turns an LLM into an agent: it gives the model tools, a wa Chef = LLM. Kitchen = harness. T3 Code = the restaurant that lets you bring whatever kitchen you want. Our MCP is a cookbook we hand the kitchen, but the chef won't open it unless you tell them to :) I wrote the long version here: [What is a harness?](https://t3.gg/blog/post/what-is-a-harness) -Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigravity, Pi, or Muse Code. [Provider setup](./install.md#providers) +Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigravity, Kiro, Pi, Muse Code, or fx. [Provider setup](./install.md#providers) ## Why use T3 Code instead of Claude Code or the Codex app? diff --git a/docs/user/html-renders.md b/docs/user/html-renders.md index 09e8143caa9c3..3a1c3de9474d1 100644 --- a/docs/user/html-renders.md +++ b/docs/user/html-renders.md @@ -12,7 +12,7 @@ Previews can load public resources such as CDN scripts, but nothing on your loca ## MCP apps -Some MCP servers return an interactive app with their tool results, following the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard. When an agent calls one of those tools, the app appears in the thread in place of the tool call, on web, desktop, and mobile. Codex and Claude support this today, for any MCP server you have configured for them. Claude needs Claude Code 2.1.301 or newer; older versions and other providers show these calls as ordinary tool calls. +Some MCP servers return an interactive app with their tool results, following the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard. When an agent calls one of those tools, the app appears in the thread below the tool call, on web, desktop, and mobile. The tool call keeps its input and result, so you can still read them when an app shows nothing. Codex and Claude support this today, for any MCP server you have configured for them. Claude needs Claude Code 2.1.301 or newer; older versions and other providers show these calls as ordinary tool calls. Apps follow your theme. An app can call tools on its own server and post a message to the thread; T3 Code asks first unless the server marks the tool as read-only, and it asks before every message. On mobile, an app also asks before opening a link, and T3 Code asks before saving a file an app offers. An app stays viewable after its agent stops, but using it needs the agent of the thread that created it running, so send a message in that thread first if the app says it is unavailable. An app that navigates away from its own page is stopped. diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 5ccb460146978..e0377c11938a5 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -227,8 +227,9 @@ manually. Custom applies separate worktree rules to the selected project or chec captures and log retention remain machine-wide. Worktrees can be removed after a chosen number of inactive days, after a thread settles, after -merging, or when they have no commits beyond the default branch. Set settled retention to 0 days -to remove a worktree at the next cleanup after settlement. In repositories without remotes, +merging, or when they have no commits beyond the default branch and their thread is settled or +archived. Set settled retention to 0 days to remove a worktree at the next cleanup after +settlement. In repositories without remotes, unchanged-worktree cleanup compares against the branch checked out in the project workspace; if that checkout has a detached HEAD, the worktree is kept. Only T3-managed worktrees are eligible. Active sessions and shared worktrees prevent removal. **Keep worktrees with local changes** defaults diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index ba1d4577a3797..20c223a75e941 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -13,10 +13,11 @@ Its branch and workspace mode come from your configured defaults. To continue in an existing worktree, use **New thread in this worktree** from the branch toolbar. On mobile, **New thread** starts in the current thread's project, or else in the -last project you opened or chose on that device. If neither is available, the -project picker opens. Turn off **Settings → General → Use last project** to -choose a project every time. When you pick a project that is on more than one -machine, the thread starts on a connected one if any is connected. +project the thread list is filtered to, or else in the last project you opened +or chose on that device. If none is available, the project picker opens. Turn +off **Settings → General → Use last project** to choose a project every time. +When you pick a project that is on more than one machine, the thread starts on +a connected one if any is connected. When you change a new thread's project, T3 Code stays in the current environment if that project exists there. Otherwise it selects an environment that has it. diff --git a/docs/user/triage.md b/docs/user/triage.md index c66bac0738e28..6e159cc7a871e 100644 --- a/docs/user/triage.md +++ b/docs/user/triage.md @@ -15,7 +15,8 @@ source for the server's version while you write. Triage runs on the machine of the thread or draft that you have open. With nothing open, it uses your primary machine if that supports triage, or else the first connected machine that does. The new thread shows the machine name, and on -mobile the palette row shows it before you start. The agent runs inside that T3 +mobile the palette row shows it before you start. If you change the machine +before you send, triage moves to that machine. The agent runs inside that T3 Code server, so it gives you any restart steps and does not do them itself. ## In a terminal diff --git a/evals/mcp-tool-use/cases/orchestration.ndjson b/evals/mcp-tool-use/cases/orchestration.ndjson index 8429099d747bc..6ba1a1cb5c065 100644 --- a/evals/mcp-tool-use/cases/orchestration.ndjson +++ b/evals/mcp-tool-use/cases/orchestration.ndjson @@ -34,6 +34,8 @@ {"id": "two-children-same-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for two Sol xhigh subagents, an Astra parent started one and refused the second, citing 'One child per named model' (#24967).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}}, "prompt": "Launch two Sol xhigh subagents. Give each a trivial task that only replies OK.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "gpt-6.1-sol", "target.options.reasoningEffort": "xhigh"}}], "minCalls": {"delegate_task": 2}, "callsMustNot": [{"tool": "delegate_task", "args": {"target.model": "~muse"}}, {"tool": "delegate_task", "args": {"target.model": "~claude"}}]}, "notes": "From #24967. One child plus the parent doing the work fails, and so does a second model in place of Sol."} {"id": "worker-counts-per-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for 20 Sol workers and 20 Luna workers, the agent started one worker per model (#25359).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"files": {"tests/flaky/retry.test.ts": "it('retry is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/upload.test.ts": "it('upload is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/session.test.ts": "it('session is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/search.test.ts": "it('search is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/billing.test.ts": "it('billing is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/webhook.test.ts": "it('webhook is flaky', async () => { /* fails 1 in 5 runs */ });\n"}}}, "prompt": "Six tests in tests/flaky/ fail now and then. Start 3 Muse Wonder Full workers and 3 Grok workers, one test file each, to find and fix the flake.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "muse-wonder-full"}}, {"tool": "delegate_task", "args": {"target.model": "grok-4.7"}}], "minCalls": {"delegate_task": 6}}, "notes": "Scaled down from the real 20 Sol + 20 Luna ask. Muse and Grok need delegate_task from every parent, so a native Sol helper cannot pass or fail it."} {"id": "linked-thread-chip-reads-there", "area": "orchestration", "kind": "guard", "pattern": "thread chip from a linked machine read on this one", "experience": "A thread chip from a linked machine names its environmentId; an agent that reads it without passing that id reads this machine, where the thread does not exist.", "rule": "The thread chip names its environmentId; t3_thread_read takes it.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [{"environmentId": "environment-vps", "label": "Hetzner VPS", "status": "reachable", "access": "auto-accept-edits", "expiresAt": "2026-12-01T00:00:00.000Z", "lastError": null}], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "t3_thread_read": {"thread": {"threadId": "thread-deploy-api", "title": "Deploy the API", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Deploy the API to the VPS and check the health endpoint."}, {"position": 2, "createdBy": "assistant", "text": "Deployed. /health returns 200, but /health/db times out after 5s: the API can't reach Postgres on 10.0.0.5:5432."}], "nextPosition": 3, "hasMore": false}}}, "prompt": "Pick up where [Deploy the API](t3-context://v1/thread/thread_deploy-api) left off. What is still failing?", "promptContext": {"records": [{"version": 1, "kind": "thread", "contextId": "thread_deploy-api", "label": "Deploy the API", "environmentId": "environment-vps", "threadId": "thread-deploy-api", "title": "Deploy the API"}]}, "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "thread-deploy-api", "environmentId": "environment-vps"}}], "notCalls": ["t3_environment_link"]}, "source": {"request": "akj on #17130: attach a linked machine's thread without dragging"}} +{"id": "vps-delegate-links-off-names-setting", "area": "orchestration", "kind": "bad", "pattern": "hidden link tools, setting never named", "experience": "With Linked environments off, the default, an agent asked to delegate to the user's VPS searched for t3_environment_link, then said the tool was not in this build and never named the setting that turns it on.", "rule": "The link tools are absent while Settings → Labs → Linked environments is off; the agent tells the user to turn it on there.", "privacy": "commit-safe", "setup": {"role": "top"}, "prompt": "Delegate this to my vps: run `uname -a` there and tell me the result. Do not edit any files here.", "expect": {"textMust": ["Labs", "Linked environments"], "notCalls": ["delegate_task", "t3_environment_links", "t3_environment_link"]}, "source": {"issue": "pingdotgg/t3code#30358"}} +{"id": "vps-delegate-links-on-calls-link", "area": "orchestration", "kind": "control", "pattern": "unlinked machine with Linked environments on", "experience": "With Linked environments on, a machine the user names that is not linked gets a t3_environment_link card, not advice to turn the setting on.", "rule": "A machine the user names that is not linked: call t3_environment_link with a hint from their words.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "t3_environment_link": {"status": "pending", "turnItemId": "turn-item-link-card-1"}}}, "prompt": "Delegate this to my vps: run `uname -a` there and tell me the result. Do not edit any files here.", "expect": {"calls": [{"tool": "t3_environment_link"}], "textMustNot": ["Labs", "([Tt]urn on|[Ee]nable)[^.\\n]*[Ll]inked environments"]}, "source": {"issue": "pingdotgg/t3code#30358"}} {"id": "background-wait-unmatched-id", "area": "orchestration", "kind": "guard", "pattern": "waits on a task ID that matches no background work, then ends the turn as if waiting", "experience": "One agent called t3_background_wait with the literal ID 'placeholder', another with a Claude subagent ID. The tool returned a normal result listing the ID under `unmatched`, so the agent said it would continue when the work came back and ended its turn. Nothing ever woke it.", "rule": "To wait for a background command or Monitor you started (tests, a build), call `t3_background_wait` with its task ID before you end your turn.", "privacy": "commit-safe", "setup": {"role": "top", "harness": "claude", "priorTurns": [{"role": "user", "text": "Run the full test suite in the background and fix whatever fails. It takes about 15 minutes."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "vp test run", "description": "Run the full test suite", "run_in_background": true}, "result": "Command running in background with ID: bq7m2x9k. Output is being written to: /tmp/claude/tasks/bq7m2x9k.output"}, {"tool": "t3_background_wait", "input": {"taskIds": ["placeholder"]}, "result": "default"}]}], "world": {"backgroundTasks": ["bq7m2x9k"], "tests": "The suite started a minute ago and runs for about 15 minutes. Until then /tmp/claude/tasks/bq7m2x9k.output lists 38 passing test files and no failures yet."}}, "prompt": "I'm heading out for a bit. Tell me what failed when it's done.", "expect": {"calls": [{"tool": "t3_background_wait", "args": {"taskIds": ["bq7m2x9k"]}}]}, "source": {"issue": "#29772"}, "notes": "The seeded wait gets T3's real result for an ID the session does not know. The tests are still running, so the only way to keep the thread waiting is a wait on bq7m2x9k. In replay, Sonnet 5.5 and Opus 5.5 also recover from main's success result, so this guards the recovery rather than reproducing the incident. Claude only: t3_background_wait is a Claude tool.", "maxSteps": 8} {"id": "background-wait-matched-id", "area": "orchestration", "kind": "control", "pattern": "waits on the right task ID, then ends the turn", "experience": "With the background command's own ID registered, ending the turn is correct: T3 keeps the thread working and wakes it when the tests finish.", "rule": "To wait for a background command or Monitor you started (tests, a build), call `t3_background_wait` with its task ID before you end your turn.", "privacy": "commit-safe", "setup": {"role": "top", "harness": "claude", "priorTurns": [{"role": "user", "text": "Run the full test suite in the background and fix whatever fails. It takes about 15 minutes."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "vp test run", "description": "Run the full test suite", "run_in_background": true}, "result": "Command running in background with ID: bq7m2x9k. Output is being written to: /tmp/claude/tasks/bq7m2x9k.output"}, {"tool": "t3_background_wait", "input": {"taskIds": ["bq7m2x9k"]}, "result": "default"}]}], "world": {"backgroundTasks": ["bq7m2x9k"], "tests": "The suite started a minute ago and runs for about 15 minutes. Until then /tmp/claude/tasks/bq7m2x9k.output lists 38 passing test files and no failures yet."}}, "prompt": "I'm heading out for a bit. Tell me what failed when it's done.", "expect": {"maxCalls": {"t3_background_wait": 1, "Bash": 3}, "notCalls": ["ScheduleWakeup"]}, "source": {"issue": "#29772"}, "notes": "Same thread as background-wait-unmatched-id, with a wait T3 matched. Guards against a fix that makes agents distrust a good wait and poll; a few looks at the output are ordinary. Claude only.", "maxSteps": 8} {"id": "settle-this-thread-after-cleanup", "area": "orchestration", "kind": "bad", "pattern": "settle read as plain English for finish", "experience": "Asked to clean up scratch files and settle this thread, the agent deleted the files and ended the turn without calling t3_thread_organize (#26749).", "rule": "A request to settle this thread calls t3_thread_organize with action settle.", "privacy": "commit-safe", "notes": "From #26749. Claude defers MCP tools, so only the tool's name is visible until ToolSearch loads it; 'settle' appears only in the t3_thread_organize description.", "setup": {"role": "top", "world": {"files": {"scratch/run-1.log": "ok\n", "scratch/run-2.log": "ok\n", "src/index.ts": "export const x = 1;\n"}}, "mocks": {"t3_thread_organize": {"settlesWhenTurnEnds": true}}}, "prompt": "Clean up the scratch files and settle this thread.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "settle"}}], "notCalls": ["t3_thread_update"]}} @@ -41,5 +43,6 @@ {"id": "settle-on-a-choice-is-not-organize", "area": "orchestration", "kind": "guard", "pattern": "settle read as plain English for finish", "experience": "Guard for the #26749 instruction: 'settle on' a choice is ordinary English and must not settle the thread.", "rule": "Only a request to settle a thread calls t3_thread_organize.", "privacy": "commit-safe", "notes": "Catches over-triggering on the settle bullet in the orchestration instructions.", "setup": {"role": "top", "world": {"files": {"src/db.ts": "export const driver = process.env.DB_DRIVER ?? 'sqlite';\n"}}}, "prompt": "We keep going back and forth on the database for this thread. Let's settle on Postgres: make it the default driver in src/db.ts.", "expect": {"notCalls": ["t3_thread_organize"]}} {"id": "settle-after-delayed-merge-waits", "area": "orchestration", "kind": "guard", "pattern": "settle before delayed work finishes", "experience": "Asked to merge a PR once its checks pass and then settle this thread, an agent following the #26749 settle bullet can settle in the first turn; a settled thread refuses watch_pull_request and drops PR-watch wakes, so the merge never happens.", "rule": "Asked to settle ... a thread, including this one: call t3_thread_organize. (the request is to settle after the merge, not now)", "privacy": "commit-safe", "notes": "From the CodeRabbit finding on #26765. Settling this thread applies at turn end, and Orchestrator.ts rejects watch wakes on a settled thread. Good: watch #123 and end the turn without settling. gh pr merge --auto plus a settle would still lose the wake that confirms the merge.", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Okay this looks good to me. Any risk merging it?"}, {"role": "assistant", "text": "Low risk. [#123](https://github.com/acme/app/pull/123) only adds an accessible title to the HTML preview frame, and the new test covers it. Two checks are still running: Check and Test Web.", "toolCalls": [{"tool": "Bash", "input": {"command": "gh pr view 123 --json title,files --jq '.title, .files[].path'"}, "result": "fix(web): HTML preview frame gets an accessible title\napps/web/src/HtmlPreview.tsx\napps/web/src/HtmlPreview.test.tsx"}, {"tool": "Bash", "input": {"command": "gh pr checks 123"}, "result": "Lint\tpass\t41s\nTypecheck\tpass\t1m2s\nCheck\tpending\t0\nTest Web\tpending\t0"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/123"}, "result": {"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "alreadyLinked": false}}]}], "mocks": {"watch_pull_request": "default", "link_pull_request": "default", "t3_thread_organize": {"settlesWhenTurnEnds": true}}, "world": {"branch": "fix/html-preview-title", "commits": [{"sha": "abc1234", "subject": "fix(web): HTML preview frame gets an accessible title"}], "diff": "diff --git a/apps/web/src/HtmlPreview.tsx b/apps/web/src/HtmlPreview.tsx\n--- a/apps/web/src/HtmlPreview.tsx\n+++ b/apps/web/src/HtmlPreview.tsx\n@@ -1,3 +1,3 @@\n export function HtmlPreview({ html }: { html: string }) {\n- return